Android: android.view.ViewRoot $ CalledFromWrongThreadException - how to solve the problem?

The application that I am currently developing communicates with the server, and the communication process works in its own flow. There are asynchronous calls - for example, login () and onLoginResponse ().

login () is called in the main action, and the response is also processed in the main action (onLoginResponse ()). The onLoginResponse () method has an updateGUIState () method that modifies layout elements:

private void updateGUIState() {

    Log.i(TAG, "executing updateGUIState");

    arrangeLayoutElements();
    txtTime.setText(mStrRecordingTime);
    if (settings.isRecording()) {
        //btnAction.setText("Stop");
        btnAction.setImageResource(R.drawable.button_stop);
    } else {
        //btnAction.setText("Capture");
        btnAction.setImageResource(R.drawable.button_record);
    }

    //set privacy level text
    if (settings.getPrivacyLevel() == 0) {
        txtPrivacyLevel.setText("Private");
    } else if (settings.getPrivacyLevel() == 1) {
        txtPrivacyLevel.setText("Public");
    }

    if (settings.isMute()) {
        muteIcon.setIconImage(R.drawable.ic_volume_off_small);
    } else {
        muteIcon.setIconImage(R.drawable.ic_volume_small);
    }

    if (mIsUploading) {
        txtUploadingText.setVisibility(View.VISIBLE);
        uploadingProgressBar.setVisibility(View.VISIBLE);
    } else {
        txtUploadingText.setVisibility(View.INVISIBLE);
        uploadingProgressBar.setVisibility(View.INVISIBLE);
    }

    if (mEncoderConnection != null) {
        txtConnectionStatus.setText("Connected");
    } else {
        txtConnectionStatus.setText("Disconnected");
    }
}

When execution reaches this method (when called from onLoginResponse ()), the application crashes and the following message is displayed in the log:

android.view.ViewRoot $ CalledFromWrongThreadException: only the source thread that created the view hierarchy can touch its views.

- , , ?

!

+5
3

Handler.

onLoginResponse() ?
, .

onLoginResponse(),

hRefresh.sendEmptyMessage(REFRESH);


    Handler hRefresh = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    switch(msg.what){
         case REFRESH:
                /*Refresh UI*/
                updateGUIState();
                break;
       }
    }
};
+17

updateGUIState() . , Runnable runOnUiThread runnable.

+3

To add bhatt4982 to the answer, you can also call handler.post(onLoginThread)where onLoginThreadis it Thread, which will be launched inside the GUI thread.

0
source

All Articles