0

In my fragment, I have an AlertDialog and a Bluetooth connection manager. I want to update the AlertDialog with the new states of the Bluetooth connection process, so I used the runOnUiThread(...) method:

getActivity().runOnUiThread(new Runnable() {
    @Override
    void run() {
        interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
            @Override
            public void OnConnectionStopped() {
                alertDialog.setMessage("Disconnected.");
            }

            @Override
            public void OnConnectionStopping() {
                alertDialog.setMessage("Stopping connection...");
            }

            @Override
            public void OnConnectionStarting() {
                alertDialog.setMessage("Connecting to device...");
            }

            @Override
            public void OnConnectionStarted() {
                alertDialog.setMessage("Streaming data...");
            }
        });
    }
});

The first time I update the AlertDialog message (OnConnectionStarting event) everything works fine, but the second time I got android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

What could be happening here?

moictab
  • 959
  • 6
  • 27

1 Answers1

1

Replace with

interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
       @Override
       public void OnConnectionStopped() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Disconnected.");
               }
           });
       }
       @Override
       public void OnConnectionStopping() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Stopping connection...");
               }
           });
       }
       @Override
       public void OnConnectionStarting() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Connecting to device...");
               }
           });
       }
       @Override
       public void OnConnectionStarted() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Streaming data...");
               }
           });
       }
   });
Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65