android - 应用程序崩溃 "Called From Wrong Thread Exception"

标签 android handler timertask

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

LOGCAT:

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

代码:

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

最佳答案

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

关于android - 应用程序崩溃 "Called From Wrong Thread Exception",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062818/

相关文章:

java - 我还可以在 android 项目中使用 eclipse 吗?

android - 将监听器添加到 Google map

Android - 监听变量变化并根据变化做某事的正确方法?

java - 在 Android 中使用 TimerTask

java - TimerTask 的问题

java - 服务在 onCreate 时崩溃并出现 nullpointerException

java - ConcurrentModificationException java.util.ArrayList$Itr.next

android - 在不重新加载数据的情况下更新 viewpager 中的 fragment View

java - 如何按条件唤醒线程

android - StopService 或删除处理程序回调(电池消耗)