hodji
hodji

Reputation: 82

Why does my app crash after hitting Reset

The timer works fine for starting then reseting and leaving the view, but if I start the time then leave the view and return and just hit Reset the app crashes. I know that most people would not hit reset when the timer is not started, but for idiot proofing I need a fix for this any suggestions?

    public void startTimer(View view) {
        final Handler handler = new Handler();
        Timer ourtimer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {

                        int sec = n % 60;
                        int min = n / 60;

                        TextView timer = (TextView) findViewById(R.id.androidtimer);
                        timer.setText("" + String.format("%02d", min) + ":"
                                + String.format("%02d", sec));

//                      timer.setText(n + " Seconds");
                        n++;
                    }
                });
            }
        };

        ourtimer.schedule(timerTask, 0, 1000);

    }

    public void stopTimer(View view) {
        timerTask.cancel();
        TextView timer = (TextView) findViewById(R.id.androidtimer);
        timer.setText("--:--");
        timerTask = null;
        n = 0;
    }

Upvotes: 0

Views: 61

Answers (1)

Endzeit
Endzeit

Reputation: 5474

I think your problem is that timerTask is null as long as you do not start the timer. So a simple if clause might help. If that's not the problem please post the exception.

   public void stopTimer(View view) {
        if(timerTask != null) {
             timerTask.cancel();
        }
        TextView timer = (TextView) findViewById(R.id.androidtimer);
        timer.setText("--:--");
        timerTask = null;
        n = 0;
    }

Upvotes: 1

Related Questions