David Elliott
David Elliott

Reputation: 113

While loop not working in Android

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

Answers (2)

C0L.PAN1C
C0L.PAN1C

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

Blackbelt
Blackbelt

Reputation: 157437

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

Upvotes: 3

Related Questions