0

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user1007522
  • 7,858
  • 17
  • 69
  • 113

3 Answers3

1

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

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

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();
user1007522
  • 7,858
  • 17
  • 69
  • 113
0

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

archetipo
  • 579
  • 4
  • 10