I'm making an Android app that turns on/off the flash light after a specified interval, by the user. It works well except when the Timer object is re-created after calling the .cancel() method for the second time, it crashes the app every time. Here's the initialization part:
Timer timer; //variable of Timer class
TimerTask timerTask; //variable of TimerTask class
And here's the method that is called when the button responsible to turn blinking on/off is pressed:
blink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
delay = Integer.valueOf(startDelay.getText().toString());
gap = Integer.valueOf(blinkDelay.getText().toString());
if(!isBlinking) { //isBlinking is a boolean to know whether to stop or re-start timer
timer = new Timer(); //I'm creating an object of Timer class every time.
isBlinking = true;
timer.schedule(timerTask, delay, gap);
}
else{
isBlinking = false;
stoptimertask(); //this will cancel the 'timer' and make it null.
}
}
});
The 'stoptimertask()' method from above code has:
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
I'm setting the 'timertask' variable of TimerTask class from the method shown below. It is called in the onCreate() method of the main activity:
public void initializeTimerTask() {
timerTask = new TimerTask() { //This is passed as the first argument to the timer.schedule() method
public void run() {//Basically turns on/off flash. Works well.
if(!state) {
turnOnFlash();
state = true;
}
else {
turnOffFlash();
state = false;
}
}
};
My question is that why does the app crash when I press the blink button the third time?
- When it is pressed for the first time, isBlinking is false, so the if block executes creating a new object of the Timer class and starting the timer.
- When it is pressed for the second time, stoptimertask() is called which cancels the timer and sets timer variable to null.
- When it is pressed again for the third time with different values for delay and gap, a new object of Timer class should be created, but the application crashes unexpectedly with a "Unfortunately the app has stopped" error. Where am I going wrong?