Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app crashing with "Called From Wrong Thread Exception"

I added this part of the code in my onCreate() method and it crashes my app. need help.

LOGCAT:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread 
that created a view hierarchy can touch its views.

CODE:

final TextView timerDisplayPanel = (TextView) findViewById(R.id.textView2);

    Timer t = new Timer();
    t.schedule(new TimerTask(){
        public void run(){
            timerInt++;
            Log.d("timer", "timer");
            timerDisplayPanel.setText("Time ="+ timerInt +"Sec");
        }
    },10, 1000);
like image 788
jeet.chanchawat Avatar asked Jun 16 '12 10:06

jeet.chanchawat


1 Answers

Only the UI thread that created a view hierarchy can touch its views.

You are trying to change the text of the UI element in Non UI Thread, so it gives exception.Use runOnUiThread

 Timer t = new Timer();
 t.schedule(new TimerTask() {
 public void run() {
        timerInt++;
        Log.d("timer", "timer");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timerDisplayPanel.setText("Time =" + timerInt + "Sec");
            }
        });

    }
}, 10, 1000);
like image 106
Samir Mangroliya Avatar answered Sep 20 '22 06:09

Samir Mangroliya