0

I am trying to design a simple timer which would run in every second and update my button's text to the remaining time. But when i run it keeps on crashing. What i know is the fault is in my button because it my code happens to run for the 1st second, then crashes after that. Here is my java code

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class information extends Activity {

Timer timer;
public Button button;
private int min = 5;
private int sec = 0;

public void onCreate(Bundle bundle){
    super.onCreate(bundle);

    setContentView(R.layout.information);
    button = (Button) findViewById(R.id.gettime);
    timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {

            if (sec == 0){
                sec = 60;
                min--;
            }
            sec--;

            if (sec >=10)
                Log.d("time",min+":"+sec);
            else Log.d("time",min+":0"+sec);    

            button.setText("ankur");
        }
    }, 10, 1000);
}

public void onPause(){
    super.onPause();
    finish();
}

public void onBackPressed(){
    super.onBackPressed();
    finish();
}

}

2 Answers2

1

button.setText("ankur"); updating ui in timer is not possible. Timer Task runs on a different thread. You can update ui only on the ui thread.

Your options

  1. Use a Handler.

  2. Use runOnUiThread.

  3. You can use a CountDownTimer depending on your need.

You can use runOnUiThread as

 runOnUiThread(new Runnable() {
    public void run() {
    button.setText("ankur")
    }
});

For the Handler

Android Thread for a timer

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

Its because you are modifying UI from background thread in this line:

button.setText("ankur");

you must use handler like:

// in your activity and then
private Handler handler = new Handler();

and in your TimerTask:

 handler.post(new Runnable() {
                    public void run(){
                        // do your UI job
                    }
              });
marcinj
  • 48,511
  • 9
  • 79
  • 100