I am making a bluetooth communication application. My MainActivity calls the loop in BluetoothConnection class (script to establish Bluetooth connection, send and receive messages), which Logs every message that it receives. I want to display this message in TextView.
I tried making TextView variable inside MainActivity, and setting its value from BluetoothConnection class but it ended with error
MainActivity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
static TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
textView = (TextView) findViewById(R.id.textView);
}
}
BluetoothConnection:
while(true)
{
try
{
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
MainActivity.textView.setText(incomingMessage);
}
catch (IOException e)
{
Log.e(TAG,"write: Error reading inputStream. " + e.getMessage());
break;
}
}
I expect the TextView to change, but application crashes with error: 'android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.'