-1

I'm doing some Http Request, and I've got this error in my logcat :

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

That is my DoInBackground code :

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;
}}

Can you help me ? Even if I comment MainActivity.textView.setText(stream);, I've got the issue.

Cœur
  • 37,241
  • 25
  • 195
  • 267
CSecchi
  • 13
  • 3

1 Answers1

1

The problem comes from the line:

MainActivity.textView.setText(stream);

You need to marshal that onto the main thread. Similar question here: Run Callback On Main Thread

Community
  • 1
  • 1
daf
  • 1,289
  • 11
  • 16