Android CountDown Timer not stop in Quiz Application

450 views Asked by At

Sorry for my poor english

Hello everyone I have made a quiz application which include 5 questions. I have made a ResultActivity page which displays result of the quiz. I have added a countDown timer of 20 sec for each question. When the Countdown timer finishes it moves to the next question automatically. When the questions are finished it should move to the ResultActivity page to display result.

I have only one issue...

If the countdown timer does not finish at 0 it still runs in the background and when you go to the third screen called ViewAnswerActivity, it returns me to the ResultActivity screen.

How do I stop the CountDown Timer after reaching the third screen? (ViewAnswerActivity)

A part of the code

ConceptActivity.class

TextView textView;
CountDownTimer countDownTimer;

@Override
Protected void onCreate (Bundle savedInstanceState) {
   Super.onCreate (savedInstanceState);
   SetContentView (R.layout.activity_concept);

    TextView = (TextView) findViewById;

     CountDownTimer = new CountDownTimer (20 * 1000,1000) {
         @Override
         Public void onTick (long millisUntilFinished) {
            TextView.setText ("" + millisUntilFinished / 1000);
         }

         @Override
         Public void onFinish () {
             Intent conceptIntent = new Intent (ConceptActivity.this, ResultActivity.class);
             StartActivity (conceptIntent);
         }

     } .start ();
 }
2

There are 2 answers

3
Starlord On

The problem is you are not stopping the timer.

          Public void onFinish () {
                        Intent conceptIntent = new Intent (ConceptActivity.this, ResultActivity.class);
                        StartActivity (conceptIntent);
                }

          public void cancel(){ 
                       if(countDownTimer != null)
                      countDownTimer.cancel(); 
                }

0
Aditya On

Add the below code whenever you move from timer activity to another activity

myTimer.cancel();
myTimer.purge();

myTimer is the variable number of type Timer.