我在项目中使用asyncTask很多,有时我会收到此错误:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
提出问题的第一堂课是:
public class GetDetails extends
AsyncTask<String, String, JSONObject> {
public String URL = null;
public Activity context;
private boolean success = false;
private String id;
@Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
// Get the application instance
AppsPlaceApplication.initInstance();
}
@Override
protected JSONObject doInBackground(String... params) {
// Looper.prepare();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = null;
try {
httppost = new HttpPost(new URI(URL));
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-type",
"application/x-www-form-urlencoded");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
String result = HelperJsonStatic.convertStreamToString(in);
}
} else {
Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
}
}
这很烦人,因为我不明白我为什么要使用looper。如果我使用那个Looper.prepare()代码行,经过一段时间它会崩溃另一个错误告诉我每个线程只有一个Looper ... 有人可以解释这件事,我做错了什么?就像走在圈子里一样。 谢谢。
答案 0 :(得分:1)
问题是您是从Toast.makeText().show()
致电doInBackground()
。您无法执行此操作,因为在后台线程上调用了doInBackground()
。您应该在Toast
中显示onPostExecute()
。