2012-06-16 124 views
11

我在我的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); 
+0

(我不知道,如何使用處理程序。) - 我讀了一些我需要使用處理程序對象。\ –

回答

32
Only the original 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); 
相關問題