Android Quiz Game - Countdown timer for each qstion

那年仲夏 提交于 2019-12-03 00:50:00

I think the activity doesn't exist anymore at a certain point when you try to make the dialog(probably when the CountDownTimer is near the end?!?).

Anyway I think finishing and starting the same activity for each question isn't such a good idea, instead you could use the current activity and simply restart the timer. For example:

public class QuestionActivity extends SherlockActivity implements
    OnClickListener {

   private CountDownTimer mCountDown;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      // ...
      mCountDown = new CountDownTimer(20000, 1000) {

        @Override
        public void onFinish() {
            // myCounter.setText("Time up!");
            timeUp(context);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            myCounter.setText("Time left: "
                    + String.valueOf(millisUntilFinished / 1000));
        }
      }.start();
      // ... 

and in the onClick callback do the same to setup a new question, stop the old timer and restart the new timer:

//check if end of game
if (currentGame.isGameOver()) {
    Intent i = new Intent(this, EndgameActivity.class);
    startActivity(i);
    finish();
} else {
    if (mCountDown != null) { 
       mCountDown.cancel();
    }  
    currentQ = currentGame.getNextQuestion();
    setQuestions();
    mCountDown = new CountDownTimer(20000, 1000) {

        @Override
        public void onFinish() {
            // myCounter.setText("Time up!");
            timeUp(context);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            myCounter.setText("Time left: "
                    + String.valueOf(millisUntilFinished / 1000));
        }
    }.start();  
}

Also, in the callback for the Dialog's Button I would first close the Dialog before finishing the Activity:

((AlertDialog) dialog).dismiss();
QuestionActivity.this.finish();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!