user1007522
user1007522

Reputation: 8118

android timer makes the app crash

I'm trying to create a Timer that does something after 5 seconds.

Now in my main activity ( I only got 1 ) I wrote this class:

class Reminder {
Timer timer;

public Reminder(int seconds) {
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds*1000);
}

class RemindTask extends TimerTask {
    public void run() {
        textFeedback.setText("test");
        timer.cancel(); 
    }
}

}

In a function (and also in my mainactivity) I create a timer as new Reminder(5).
After 5 seconds the application crashes.
I don't see whats wrong, because I do it in normal java apps like this.

Upvotes: 0

Views: 545

Answers (3)

user1007522
user1007522

Reputation: 8118

Thanks.

Solved it like this:

         new CountDownTimer(5000, 1000) {

             public void onTick(long millisUntilFinished) {
                 //textFeedback.setText("seconds remaining: " + millisUntilFinished / 1000);
             }

             public void onFinish() {
                 textFeedback.setText("");
             }
          }.start();

Upvotes: 1

Raghunandan
Raghunandan

Reputation: 133560

Not sure where you have initialized textFeedback.

textFeedback.setText("test"); cannot update ui from a timer task. Timer task runs on a non ui thread. Ui can be updated only on ui thread.

Your options use a Handler or runOnUiThread.

Note runOnUiThread is a method of Activity class. Requires Activity Context

More info

Android Thread for a timer

Upvotes: 1

archetipo
archetipo

Reputation: 579

when the class Remainder is istatiate not know the var textFeedback , becaouse you nees to pass the owmer of the textFeedback

Upvotes: 0

Related Questions