android - 为什么 onPostExecute 在 AsyncTask 中的 doInBackground 完成之前执行

标签 android android-asynctask

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

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 中的警告或调试页面。此外,您应该分别打印这两个异常。

关于android - 为什么 onPostExecute 在 AsyncTask 中的 doInBackground 完成之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869795/

相关文章:

java - 如何在项目编译之前将projectS的源代码复制到项目中?

Android 引用样式属性 - 触发 ResourceNotFoundException

android - 清除 SingleChoice ListView 选择

android - 在 Android 上运行 elf 可执行文件

android - 互联网连接丢失时不停止读取 Inputstream

android - 通过柄中的不同具体类绑定(bind)接口(interface)?

android 在 ListView 中更改行项目 View 相关的一个 fragment

android - MqttAndroidClient - onFailure

java - android在异步任务中更新自定义 View

android - 如何关闭 ASyncTask 的 Activity ?