Reputation: 27
my code is:
ou=100
final Timer t=new Timer();
TimerTask tt=new TimerTask() {
@Override
public void run() {
ou-=10;
if(ou==0)
btnstart.setText(btnstart.getText().toString()+"t");
}};
t.scheduleAtFixedRate(tt, 2000, 2000);
but when I run this program when change btnstart.text program will be close with this error "unfortunately, has stopped"
this is my log cat:
07-01 15:27:30.714: W/dalvikvm(973): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
07-01 15:27:30.786: E/AndroidRuntime(973): FATAL EXCEPTION: Timer-0
07-01 15:27:30.786: E/AndroidRuntime(973): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
07-01 15:27:30.786: E/AndroidRuntime(973): at android.os.Handler.(Handler.java:121)
07-01 15:27:30.786: E/AndroidRuntime(973): at android.widget.Toast$TN.(Toast.java:322)
07-01 15:27:30.786: E/AndroidRuntime(973): at android.widget.Toast.(Toast.java:91)
07-01 15:27:30.786: E/AndroidRuntime(973): at android.widget.Toast.makeText(Toast.java:238)
07-01 15:27:30.786: E/AndroidRuntime(973): at ir.maghsoodi.reminders.MainActivity$1$1.run(MainActivity.java:45)
07-01 15:27:30.786: E/AndroidRuntime(973): at java.util.Timer$TimerImpl.run(Timer.java:284)
Upvotes: 1
Views: 668
Reputation: 970
You can not update the UI from another thread, you need to use an Handler as explained here, or (much easier in my opinion) use the eventbus library
Upvotes: 1
Reputation: 14847
TimerTask
is executed in another Thread (TimerThread) and you can't update UI
elements from a thread which is not the main.
Use btnstart.post( Runnable )
to execute the code inside UI Thread.
Example
if(ou==0) {
btnstart.post(new Runnable() {
@Override
public void run() {
btnstart.setText(btnstart.getText().toString()+"t");
}
});
}
Upvotes: 2