Android:Android.view.ViewRoot$CalledFromErrorThreadException-如何解决问题?

Android:Android.view.ViewRoot$CalledFromErrorThreadException-如何解决问题?,android,layout,multithreading,Android,Layout,Multithreading,我目前正在开发的一个应用程序正在与服务器通信,通信进程在自己的线程中运行。有异步调用-例如login()和onLoginResponse() login()在主活动中调用,响应也在主活动中处理(onLoginResponse()。在onLoginResponse()方法中,有一个updateGUIState()方法,用于修改布局元素: private void updateGUIState() { Log.i(TAG, "executing updateGUIState");

我目前正在开发的一个应用程序正在与服务器通信,通信进程在自己的线程中运行。有异步调用-例如login()和onLoginResponse()

login()在主活动中调用,响应也在主活动中处理(onLoginResponse()。在onLoginResponse()方法中,有一个updateGUIState()方法,用于修改布局元素:

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");
    }
}
当执行到达此方法时(从onLoginResponse()调用时),应用程序崩溃,日志显示以下消息:

android.view.ViewRoot$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图

有人知道如何在修改布局和修复问题之前修改逻辑以切换到适当的线程吗


谢谢

updateGUIState()
需要在UI线程上运行。一种可能的解决方案是在
Runnable
中实现GUI更新,并使用Runnable调用
rununuithread
方法。

尝试
处理程序

onLoginResponse()
是回调函数吗?
如果是,问题可以由处理程序解决。

onLoginResponse()中

hRefresh.sendEmptyMessage(REFRESH);


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

要添加到bhatt4982的响应中,您还可以调用
handler.post(onLoginThread)
,其中
onLoginThread
是一个
线程,它的runnable将在GUI线程中运行。

我希望我很长时间都能找到这个答案,我遇到了完全相同的问题,花了大约一周的时间才找到解决方案,这正是你提到的我发现这个例外至少有5个不同的答案。只有这个对我有用!