2013-08-30 107 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);