Note that there are some explanatory texts on larger screens.

plurals
  1. POTextView update crashes application
    text
    copied!<p>This has been discussed many times before, but it is still a real pain for me. </p> <p>PROBLEM: App crashes whenever I try to update text it TextView</p> <p>CONTEXT: Im using bluetooth app with multi threads. The "listening" thread (ConnectedThread) sends Handler whenever new message is obtained. This handler is then resolved in main Activity, where the TextView is initialized.</p> <p>WHAT I HAVE TRIED/CHECKED SO FAR:</p> <ol> <li>I think I am not updating TextView from different activity/thread</li> <li>the TextView is initialized after setContentView(R.layout.main); (well, in other post, this was causing the trouble)</li> </ol> <p>CODE: (in short)</p> <p>MAIN ACTIVITY</p> <pre><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); &lt;----- THIS IS THE ISSUE break; ....... .... } } }; </code></pre> <p>CONNECTED THREAD</p> <pre><code>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 ... } } } </code></pre> <p>Primarily this was the function respossible for showing incoming messages </p> <pre><code>Toast.makeText(getApplicationContext(), "Received: " + readMessage, Toast.LENGTH_SHORT).show(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload