【问题标题】:How to fix "android.view.ViewRootImpl$CalledFromWrongThreadException"如何修复“android.view.ViewRootImpl$CalledFromWrongThreadException”
【发布时间】:2014-12-03 09:08:15
【问题描述】:

我想修复如下错误:

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

这是我的代码。

公共类 MainActivity 扩展 Activity {

@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    onShowMessage();
}

public void removeContent() {
    LinearLayout list = (LinearLayout) findViewById(R.id.linearlayout_list);
    list.removeAllViews();
}

public void onShowMessage() {
    Thread myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            String id = "id1";
            String message = "message1";
            String response = HTTPUtils.HTTPPost(Global.MESSAGE_URL, 
                    "id", id, 
                    "message", message);
            process(response);
        }
    });
    myThread.start();
}

private void process(String response) {
    if (response == null || response.equals("")) {
        return;
    } else {
        try {
            JSONObject json = null;
            try {
                json = FbUtil.parseJson(response);
            } catch (FacebookError e) {
                showErrorMessage();
            }
            if (json.has("exception")) {
                showErrorMessage();
                return;
            } else {
                Global.list = JsonParser.getInfo(json);
                removeContent();
                initView();
                return;
            }
        } catch (JSONException e) {

        }
        return;
    }
}

}

removeContent() 发生错误;

请帮帮我。

【问题讨论】:

    标签: android multithreading


    【解决方案1】:

    您正在不同线程中更新视图

    removeContent(); initView();

    在 UI 线程中调用这两个方法。

        runOnUiThread(new Runnable() {
    
            @Override
            public void run() {
                removeContent();
                initView();             
            }
        });
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多