I was trying to do something else but kept on removing code thinking that simplifying things will help in identifying my mistake. This is what I am left with (after a lot of simplification) and still I am not getting it why it is not doing it is supposed to!
public class MyOwnTimerActivity extends Activity {
int timeLeft = 5;
TextView timerTextView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button timerButton = (Button) findViewById(R.id.button1);
timerTextView = (TextView) findViewById(R.id.timerText);
Thread timer = new Thread() {
public void run() {
try {
sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally{
timerTextView.setText("something");
}
}
};
timer.start();
}
}
Error: The application crashed after 3 seconds i.e. after timer goes off.
Ah, yes)) This is because you try to modify UI from non UI-thread
Update:
There are several ways to modify UI from another thread:
Handlerclass with overridinghandleMessage()methodActivityclass with callingrunOnUI()method, passing thereRunnableobject in whichrun()method you modify UIView.post()orView.postDelayed()methodsThe last variant is the most convenient in your case. Modify your code in such manner: