1

I have a TextView that is updated but I cannot see the refresh until i minimize and reopen the application. here is the code that performs that.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
    Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();

    for (BluetoothDevice device : pairedDevices) {

        device.connectGatt(this, true, new BluetoothGattCallback() {

            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                TextView state;

                switch (newState) {

                    case BluetoothProfile.STATE_CONNECTED: 
                        state = (TextView)findViewById(R.id.state);
                        state.setText("Connected = True");
                        state.setTextColor(Color.GREEN);
                        break;

                    case BluetoothProfile.STATE_DISCONNECTED:
                        state = (TextView)findViewById(R.id.state);
                        state.setText("Connected = False");
                        state.setTextColor(Color.RED);
                        break;
                }
            }
        });
    }
}

What I need to refresh that TextView? I'm doing anything else wrong?

Lechucico
  • 1,914
  • 7
  • 27
  • 60

1 Answers1

6

You should update the TextView in the main (ui) thread, like this

    runOnUiThread(new Runnable() {
        public void run() {
            state.setText("Connected = False");
            state.setTextColor(Color.RED);
        }
    });

or if you project is configured to support java 8 you can write it more concisely

    runOnUiThread(() -> {
       state.setText("Connected = False");
       state.setTextColor(Color.RED);
    });
       
Crispert
  • 1,102
  • 7
  • 13
  • Do I have to do this whenever I need to update the view? – Lechucico Feb 19 '18 at 16:50
  • Yes, all views must be updated on the UI thread since android's UI framework is single threaded. If you find this approach too verbose you can try others like the ones mentioned here https://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread. You could also use a reactive (RxJava/RxAndroid) or publish/subscribe approach and specify the thread to process the received event through an annotation. I am pretty fond of https://github.com/greenrobot/EventBus for its ease of use. – Crispert Feb 20 '18 at 13:36