Search code examples
javaandroidloopscountdowntimer

Looping through Countdown


I am trying to loop through a CountDownTimer several times but the problem is the loop finishes before the timer finishes so the countdown only runs once.

function that loops through the timer

private void doWorkout(){
    int currentSet = 1;
    for (int i = 1; i<= NUMBER_OF_SETS; i++){
        Log.d(TAG, "doWorkout: iteration " + i);
        startWorkoutTimer();
        //make for loop sleep till timer is done
    }

}

private void startWorkoutTimer() {
    mWorkoutCountDownTimer = new CountDownTimer(START_TIME, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mWorkRestLabel.setText("Work");
            mWorkRestLabel.setVisibility(View.VISIBLE);
            mTimeLeftInMillis = millisUntilFinished;
            updateCountDownText();
        }

        @Override
        public void onFinish() {
            mWorkoutTimerRunning = false;
            mButtonStartPause.setText("start");
            mButtonStartPause.setVisibility(View.INVISIBLE);
            mButtonReset.setVisibility(View.VISIBLE);
            mWorkRestLabel.setVisibility(View.INVISIBLE);
            startRestTimer();
        }
    }.start();

    mWorkoutTimerRunning = true;
    mButtonStartPause.setText("pause");
    mButtonReset.setVisibility(View.INVISIBLE);
}

Solution

  • The for loop doesn't wait for the CountDownTimer to finish. So it is starting all the timers at once, so it looks like it only ran once.

    To fix this, instead of a loop, you have to start a new timer in startRestTimer() (which as per your code is in onFinish() & runs after a timer is finished) when NUMBER_OF_SETS is > 0 and decrement the NUMBER_OF_SETS.

    So, it will run one after another.

    Hope it helps.