2013-08-30 106 views
0

這已被討論過很多次,但它仍然是我真正的痛苦。TextView更新崩潰應用程序

問題:應用程序崩潰時,我嘗試更新它的文本TextView的

背景:使用藍牙的應用程序的多線程林。 「偵聽」線程(ConnectedThread)在獲得新消息時發送Handler。該處理程序然後在初始化TextView的主Activity中解析。

我曾嘗試/ CHECKED至今:

  1. 我想我不會從不同的活動更新的TextView /線程
  2. TextView的的setContentView(R.layout.main)之後進行初始化; (當然,在其他崗位,這是造成麻煩)

CODE:(簡稱)

主要活動

public class BluetoothActivity extends Activity { 

private TextView mDisplay; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.main); 

     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     ..... 
     .. 
    } 


    private void setupApp() { 

     // Initialize the BluetoothService to perform bluetooth connections 
     // This is where the Handler is passed to "ConnectedThread" (it is part of  
      mService) 
     mService = new BluetoothService(this, mHandler); 
    } 


    // The Handler that gets information back from the BluetoothService 
    private final Handler mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 

      ...... 

      case MESSAGE_READ: 
       byte[] readBuf = (byte[]) msg.obj; 
       // construct a string from the valid bytes in the buffer 
       String readMessage = new String(readBuf, 0, msg.arg1); 
       if(D) Log.d(TAG, "Received: " + readMessage); 

       mDisplay.setText(readMessage); <----- THIS IS THE ISSUE 

       break; 
       ....... 
       .... 
      } 
     } 
    }; 

連螺紋

private class ConnectedThread extends Thread { 

    ...... 

    public void run() { 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 

       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch ... 
      } 
     } 
    } 

這主要是該功能可以顯示收到的消息

Toast.makeText(getApplicationContext(), "Received: " + readMessage, 
    Toast.LENGTH_SHORT).show(); 

回答

0
解決

我忘記設置填充mDisplay =(TextView的)findViewById(R.id.Display);