0

我在我的项目中经常使用 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 ...有人可以解释一下这件事以及我做错了什么吗?就像在绕圈子走一样。谢谢你。

4

1 回答 1

1

问题是您Toast.makeText().show()doInBackground(). 您不能这样做,因为doInBackground()在后台线程上调用。您应该改为显示Toastin onPostExecute()

于 2013-09-28T23:05:39.563 回答