Reputation: 125
So I looked at so many sources and whenever there is such a problem, it's because the countdowntimer is trying to get cancelled from inside the ontick. This is not my issue. I have the countdowntimer in a runnable. I cancel the timer, I cancel the runnable and it still somehow gets called. Here is some code below. I appreciate any help!
Handler myHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
CountDownTimer countdownTimer = new CountDownTimer(difference - (1000 * 60) + 2000, 60000) {
public void onTick(long millisUntilFinished) { // some work here
}
public void onFinish() {
// some other work here
};
data.get(i).setCountDownTimer(countdownTimer);
data.get(i).getCountDownTimer().start();
}
};
data.get(i).setHandler(myHandler);
data.get(i).setRunnable(runnable);
data.get(i).start(2000);
The start function is basically:
public void start(int milliseconds){
handler.postDelayed(runnable, milliseconds);
}
data is just a list of objects where each has its own runnable, handler and countdowntimer.
Here is what I do when I cancel:
data.get(i).getCountDownTimer().cancel();
data.get(i).terminate();
The terminate function is basically:
public void terminate() {
handler.removeCallbacks(runnable);
}
Someone please tell me why the countdowntimer somehow still runs after I cancel it the way I do above; thanks!
UPDATE
In onFinish, I have another countdown that is on a smaller interval. Is onFinish called when I cancel a CountDownTimer? Otherwise I'm really out of ideas! Thanks.
Upvotes: 2
Views: 306
Reputation: 125
This was a very silly mistake on my end. When I was removing an object from the data list, I was cancelling the alarm via: data.get(i).getCountDownTimer().cancel(); And then I remove the object, and notifyitemremoved. The mistake is that I should notifyitemchanged, and in the onbind, I should cancel it. Then I should remove the entry safely knowing the CTD has been cancelled. Anyway, thanks everyone for the input.
Upvotes: 0
Reputation: 38289
Although you made a good effort to post the relevant pieces of your code, I'm having a hard time imagining how they all fit together. For example, when you create the Runnable
for each data object, are the calls to set and start the countdown timer really in the run()
method as shown? I'm wondering how data
and i
are accessible at that point. And if they are truly accessible, how you know that i
will have the desired value when the Runnable
comes out of the queue and executes?
I agree that cancel() should cause the CountDownTimer
to stop. Note however that if start()
is called after cancel()
the timer will start anew--it's not a one-shot. If a bug is causing start()
to be called a second time, it will look like the cancel didn't work.
All I can suggest is that you add a bunch of Log
statements throughout your code to confirm your assumptions about when timers are starting and being cancelled, and what the value of i
is for each instance.
Upvotes: 0