ostExecute在AsyncTask中的doInBackgr

ostExecute在AsyncTask中的doInBackgr

本文介绍了为什么onPostExecute在AsyncTask中的doInBackground完成之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个AsyncTask来从服务器端获取一些数据.但是它在"IOUtils.copy((response_.getEntity().getContent()),writer);"行的onPostExecute()中报告了一个空指针异常.我使用一些日志来查看发生了什么,发现打印了日志1和3,但没有打印日志2.为什么onPostExecute是在client.exected()完成之前执行的?任何人都可以提出建议吗?

I was trying to create a AsyncTask to get some data from server side. But it reports a Null pointer exception in onPostExecute() in line "IOUtils.copy((response_.getEntity().getContent()), writer);" I use some logs to see what happens and found log 1 and 3 were printed but log 2 was not. Why onPostExecute was executed before client.executed() finish? Anyone can give some suggestions?

private class GetForm extends AsyncTask<String, Integer, Object> {
    private HttpResponse response_;
    private Exception exception_;
    private String url_;

    public GetForm(String url) {
        super();
        url_ = url;
    }
    protected Object doInBackground(String... params) {
        try {
            Log.i("mylog","inside doInbackground 1.");
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url_);
            response_ = client.execute(request);
                            Log.i("mylog","inside doInbackground 2.");

        } catch (Exception e) {
            exception_ = e;
        }
        return response_;
    }
    @Override
    protected void onPostExecute(Object o) {
        // Your current UI stuff here.
        Log.i("mylog","inside onPostExecute 3.");
        StringWriter writer = new StringWriter();
        try{
            IOUtils.copy((response_.getEntity().getContent()), writer);
        ......

        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

推荐答案

不太可能先调用onPostExecute(),而且不太可能在您的doInBackground()中引发异常.还有为什么Log 2没有被调用打印.在LogCat中检查警告"或调试"页面.另外,您应该分别打印两个例外.

It's unlikely that onPostExecute() was called first, and more likely that an exception was thrown in your doInBackground()..and also why Log 2 wasn't printed. Check the Warning or Debug pages in your LogCat. Also, you should print both exceptions separately.

这篇关于为什么onPostExecute在AsyncTask中的doInBackground完成之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:00