Reputation: 113
I'm trying to make a while loop that will make a number count up. However, when the app runs, it just crashes. Here's the code I used:
Thread Timer = new Thread(){
public void run(){
try{
int logoTimer = 0;
while(logoTimer != 5000){
sleep(100);
logoTimer = logoTimer + 1;
button.setText(logoTimer);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
Timer.start();
Am I doing something wrong? Do I need to add something in the .xml file? Thanks in advance.
Upvotes: 0
Views: 217
Reputation: 12243
You need to run the setText for the button on the UI thread!
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
button.setText(logoTimer);
}
});
Upvotes: 0
Reputation: 157437
it does crash for two reasons
setText(int)
, which looks up for a string inside string.xml
. If it does not exits, the ResourceNotFoundException
will be thrown. Edit: as G.T. pointed out you can use button.setText(logoTimer+"")
; to avoid the exception at point 2
Upvotes: 3