我正在做一些HTTP請求,並且我得到這個錯誤在我的logcat:android.view.ViewRootImpl $ CalledFromWrongThreadException:多線程錯誤在安卓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);
,我也遇到了這個問題。
'MainActivity.textView'?你是否聲明你的TextView是靜態的? – Blackbelt