app crashing with “Called From Wrong Thread Exception”

蹲街弑〆低调 提交于 2019-11-27 23:41:28

问题


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);

回答1:


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);


来源:https://stackoverflow.com/questions/11062818/app-crashing-with-called-from-wrong-thread-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!