Issue
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.
Solution
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
Answered By - daf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.