应用程序崩溃与“从错误的线程异常调用”

时间:2012-06-16 10:58:57

标签: android handler timertask

我在onCreate()方法中添加了这部分代码,它崩溃了我的应用。 需要帮助。

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 个答案:

答案 0 :(得分:33)

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

您正在尝试更改非UI线程中UI元素的文本,因此它提供了异常。使用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);