Android中的多线程错误:CalledFromErrorThreadException
我正在执行一些Http请求,我的logcat中有一个错误: 原因:android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图 这是我的背景代码:Android中的多线程错误:CalledFromErrorThreadException,android,multithreading,android-asynctask,httprequest,Android,Multithreading,Android Asynctask,Httprequest,我正在执行一些Http请求,我的logcat中有一个错误: 原因:android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图 这是我的背景代码: public class AsyncClass extends AsyncTask { StringBuilder result = new StringBuilder(); String stream = null; public String res
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(流)代码>,我有问题。问题来自以下行:
MainActivity.textView.setText(stream);
您需要将其封送到主线程。类似问题如下:
MainActivity.textView
?您是否声明了TextView静态?我使用了thx daf btw的onPostExecute()
方法,而不是封送