2012-06-16 15 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); 
関連する問題