TextView更新崩溃了应用程序

时间:2013-08-30 15:09:06

标签: android textview

之前已经讨论了很多次,但对我来说这仍然是一个真正的痛苦。

问题:每当我尝试将文本更新为TextView

时,应用程序崩溃

背景:我正在使用多线程的蓝牙应用程序。每当获得新消息时,“监听”线程(ConnectedThread)就发送Handler。然后在主Activity中解析此处理程序,其中初始化TextView。

我已经尝试过/检查过了什么:

  1. 我认为我没有从不同的活动/线程
  2. 更新TextView
  3. 在setContentView(R.layout.main)之后初始化TextView; (好吧,在其他帖子中,这造成了麻烦)
  4. 代码:(简而言之)

    主要活动

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

1 个答案:

答案 0 :(得分:0)

解决

我忘了设置mDisplay =(TextView)findViewById(R.id.Display);