Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
If you're getting a crash you should include the stack trace in your question. –  Michael Jul 22 '14 at 16:38

2 Answers 2

it does crash for two reasons

  1. you are touching the UI from a thread that is not the UI Thread
  2. you are calling 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

share|improve this answer
    
Just to complete your answer, the second point can be easily solved by casting the int to String like this: button.setText(logoTimer+""); –  G.T. Jul 22 '14 at 16:41
    
@G.T. thanks I edited my answer –  Blackbelt Jul 22 '14 at 16:42
    
when I use button.setText(logoTimer+"");, it works for a second or two and then crashes (before it crashes, it updates the button). –  David Elliott Jul 22 '14 at 17:19

You need to run the setText for the button on the UI thread!

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
         button.setText(logoTimer);
    }
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.