Android中的多线程错误:CalledFromWrongThreadException

时间:2016-07-05 09:27:10

标签: android multithreading android-asynctask httprequest

我正在做一些Http请求,我在logcat中遇到了这个错误:

  

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

这是我的DoInBackground代码:

public class AsyncClass extends AsyncTask {
StringBuilder result = new StringBuilder();
String stream = null;
public String rest_Url = "https://....." ;

@Override
protected Object doInBackground(Object[] params) {
    HttpURLConnection client = null;

    try {
        URL url = new URL(rest_Url);
        client = (HttpURLConnection) url.openConnection();
        client.setRequestMethod("GET");
        client.setDoOutput(true);


        int responseCode = client.getResponseCode();
        switch (responseCode){
            case 200:
                String success = "SUCCESS";
                System.out.println(success);

                InputStream inputPost = new BufferedInputStream(client.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputPost));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                stream = result.toString();
                MainActivity.textView.setText(stream);
                break;

            default:
                String failure = "FAILURE";
                System.out.println(failure);
                break;
        }


    } catch (IOException e) {
        e.printStackTrace();}

    finally {
        if(client != null){
            client.disconnect();
        }
    }

    return null;
}}
你能帮帮我吗? 即使我发表评论MainActivity.textView.setText(stream);,我也遇到了问题。

1 个答案:

答案 0 :(得分:1)

问题来自这条线:

MainActivity.textView.setText(stream);

您需要将其编组到主线程上。类似的问题: Run Callback On Main Thread