0

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.'

Osicat
  • 1
  • 2

1 Answers1

0

You need to pass the MainActivity's context to the BluetoothConnection.class

After that you can do:

    TextView txtView = (TextView) ((MainActivity)context).findViewById(R.id.your_tv);
    txtView.setText("Hello");
Yash
  • 3,438
  • 2
  • 17
  • 33