0
使用Looper.prepare我使用的AsyncTask了很多在我的項目,有時我收到此錯誤:中的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 ... 有人可以解釋這件事,我做錯了什麼?這就像走在圈子裏。 謝謝。
現在看起來好了。希望這仍然是這樣。謝謝 – user1140656
@ user1140656它會的。 100%的保證。 :) –