1

In a certain Activity have a TextView variable named timeText, which needs to be changed after 3 seconds have passed after the Activity was opened.

This is the code I wrote:

TextView timeText = (TextView) findViewById(R.id.tvTimeText);
Thread timer = new Thread() {
        public void run() {
            try {
                sleep(3000);
                timeText.setText("3");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
};
timer.start();

However this gave me this error: "Cannot refer to a non-final variable timeText inside an inner class defined in a different method"

So I changed the modifier of the TextView to final and tried again. However, now the application crashes when this activity is started.

Akshay Damle
  • 1,220
  • 3
  • 18
  • 31
  • Try and use runOnUiThread. Here is an example: http://stackoverflow.com/questions/11140285/how-to-use-runonuithread – AnOldSoul Jan 07 '14 at 14:17

2 Answers2

3

Cannot update ui from a non ui thrad

 timeText.setText("3");

Use runOnUiThread or Handler.

runOnUiThread(new Runnable() {

        public void run() {
            timeText.setText("3");

        }
    });

You can declare timeText as a instance variable and you need not have final modifier.

TextView timerText;
protectected void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.mylayout);
  timeText = (TextView) findViewById(R.id.tvTimeText);
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
2

Use a handler and a runnable:

final Runnable runnable = new Runnable() {
    public void run() {
        timeText.setText("3");        
    }
};

Handler handler = new Handler();
handler.postDelayed(runnable , 3000);
Devrim
  • 15,345
  • 4
  • 66
  • 74