android - AsyncTask doInBackground 有时只返回空指针异常

标签 android nullpointerexception android-asynctask

出现此错误:

 java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Caused by: java.lang.NullPointerException
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:79)
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more

这是我的 AsyncTask...它只在特定时间对某些用户崩溃...不知道为什么。也许他们在查询中途失去了互联网连接?我在这里做错了什么?这是我的代码:

private class DownloadSite extends AsyncTask<String, Integer, String> {
        private HttpResponse response;
        private InputStream in;
        private Context context;
        private String html;
        private ProgressDialog progress;


        @Override
        protected String doInBackground(String... params) {

            in = null;

            String url = "aURLGOESHERE_BUTI'MCENSORING"                                 + params[0] + "";

            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            HttpResponse response = null;

            try {
                response = client.execute(request);
            } catch (ClientProtocolException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                in = response.getEntity().getContent();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();

            }
            html = null;

            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(in));
            } catch (Exception e) {

                this.publishProgress();
                this.cancel(true);

                e.printStackTrace();
            }

            StringBuilder str = new StringBuilder();
            String line = null;

            try {
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            html = params[0] + str.toString();

            return html;

        }

        @Override
        protected void onPreExecute() {

            progress = new ProgressDialog(BrowseListActivity.this);
            progress.setIndeterminate(true);
            progress.setMessage("Loading...");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {

            CharSequence text = "Connection interrupted...please try again";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(getApplicationContext(), text,
                    duration);
            toast.show();
        }

        @Override
        protected void onPostExecute(String html) {
            progress.dismiss();

            Context context = BrowseListActivity.this;
            Intent stopViewer = new Intent(context, StopActivity.class);
            stopViewer.setData(Uri.parse(html + ""));
            context.startActivity(stopViewer);

        }

    }

最佳答案

您做错的一件事是在发生错误后继续执行 doInBackground,这使得无法有意义地继续。例如:

try {
    response = client.execute(request);
} catch (ClientProtocolException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

如果这引发异常,response 将是 null 并且没有必要继续进行。您将在下一个代码块中生成一个 NullPointerException。那不会是致命的,因为您在那里捕获了所有异常。但是,进一步地,这种模式会重复出现,而您并没有捕捉到所有异常。

您应该提前退出,返回 null 作为 String 结果。然后,您可以在 onPostExecute 中测试 null 并以优雅的方式让用户知道发生了什么。

关于android - AsyncTask doInBackground 有时只返回空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8996957/

相关文章:

android应用程序root或系统权限

java - 向 Java Applet 添加按钮

java - 如何为不同的进程运行相同的AsyncTask类?

java - 当参数字符串为 null 时,int compareTo() 应该返回什么?

java - HashMap 获取一个元素并设置为自定义值类型

android - 显示进度对话框的登录屏幕并允许更改屏幕方向

android - 异步任务后更新 ListFragment

java - Android 中将首先处理哪些代码?

android - 在没有 Bitmap.CompressFormat 的情况下将位图转换为字节数组

java - 在 Android Studio 上使用 Android 和 Google App Engine