jakub
jakub

Reputation: 3844

CountDownTimer onTick() can't update a member of class

I update a field inside CountDownTimer in onTick() method. However, the field is always 0. Do you have an idea what is causing a problem?

public class Counter {

    private static final long SECOND_MS = 1000;
    private static final long MINUTE_MS = 60 * SECOND_MS;
    private static final long TOTAL_TIME_MS = 5 * MINUTE_MS;

    public long mSecondsSinceLastPick;

    public long getSecondsSinceLastSchedulerStarted() {
        Timber.d( String.format("get mSecondsSinceLastPick = %s", mSecondsSinceLastPick) );
        return mSecondsSinceLastPick;
    }


    private CountDownTimer mCountDownTimer = new CountDownTimer(TOTAL_TIME_MS, SECOND_MS) {

        public void onTick(long millisUntilFinished) {
            Timber.d( String.format("onTick mSecondsSinceLastPick = %s", mSecondsSinceLastPick) );
            mSecondsSinceLastPick = (TOTAL_TIME_MS - millisUntilFinished) / SECOND_MS;
        }

        public void onFinish() {
        }
    };

public void startCounting() {
    mCountDownTimer.start();
}
}

[EDITED] Log output looks like

06-19 15:42:57.293 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 4
06-19 15:42:58.293 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 5
06-19 15:42:59.299 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 6
06-19 15:43:00.320 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 7
06-19 15:43:01.321 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 8
06-19 15:43:01.507 9994-9994/com.nav.survey D/GroundTruthReminderManager:22: get mSecondsSinceLastPick = 0
06-19 15:43:02.322 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 9
06-19 15:43:03.324 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 10
06-19 15:43:04.325 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 11

Upvotes: 0

Views: 81

Answers (2)

jakub
jakub

Reputation: 3844

The Problem is with creating my counter. I use Dagger @Singleton annotation to provide Counter, however, anyway 2 instances of Counter were created and it caused a problem.

Upvotes: 0

Martin De Simone
Martin De Simone

Reputation: 2148

The problem is that you dont start the timer

 mCountDownTimer.start();

or

private CountDownTimer mCountDownTimer = new CountDownTimer(TOTAL_TIME_MS, SECOND_MS) {

    public void onTick(long millisUntilFinished) {
        Timber.d( String.format("onTick mSecondsSinceLastPick = %s", mSecondsSinceLastPick) );
        mSecondsSinceLastPick = (TOTAL_TIME_MS - millisUntilFinished) / SECOND_MS;
    }

    public void onFinish() {
    }
}.start();

Upvotes: 1

Related Questions