Humayun Kabir
Humayun Kabir

Reputation: 611

sleep function not working

I want to show 1 to 100 in a changeable text. I like to use sleep()function so that it looks like that it is increasing form 1 to 100. my code is

for(int i= 0;i<100;i++) {
    scorelevel.setText(String.valueOf(i));
    try{
        Thread.sleep(1000);
    }catch (InterruptedException e) {
        e.printStackTrace();
    }
}

but it did not show properly. Any help or suggestion is appreciated.

Upvotes: 2

Views: 839

Answers (4)

overbet13
overbet13

Reputation: 1674

You could use a TimerTask (link), too.

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

You can start counter using runOnUiThread to update textView as:

private boolean mClockRunning=false;
private int millisUntilFinished=0;
public void myThread(){
            Thread th=new Thread(){
             @Override
             public void run(){
              try
              {
               while(mClockRunning)
               {
               Thread.sleep(1000L);// set time here for refresh time in textview
               YourCurrentActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 // TODO Auto-generated method stub
                     if(mClockRunning)
                     {
                     if(millisUntilFinished==100)
               {
               mClockRunning=false;
               millisUntilFinished=0;
                }
                else
                {
               millisUntilFinished++;
               scorelevel.setText(String.valueOf(millisUntilFinished));//update textview here

               }
             }

            };
          }
              }catch (InterruptedException e) {
            // TODO: handle exception
             }
             }
            };
            th.start();
           }

Upvotes: 0

Arun George
Arun George

Reputation: 18592

Use Timer and TimerTask to perform any time based task.

Upvotes: 0

Zang MingJie
Zang MingJie

Reputation: 5275

Don't block UI thread, use AsyncTask instead

Upvotes: 5

Related Questions