2

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.

Cata
  • 11,133
  • 11
  • 65
  • 86
Humayun Kabir
  • 561
  • 2
  • 13
  • 27

4 Answers4

5

Don't block UI thread, use AsyncTask instead

Zang MingJie
  • 5,164
  • 1
  • 14
  • 27
0

Use Timer and TimerTask to perform any time based task.

Arun George
  • 18,352
  • 4
  • 28
  • 28
0

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();
           }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

You could use a TimerTask (link), too.

overbet13
  • 1,654
  • 1
  • 20
  • 36