AsyncTask doInBackground returning a nullpointerex

2019-08-02 06:35发布

Getting this error:

 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

Here's my AsyncTask...it crashes only for some users at particular times...not sure why. Perhaps they lose their internet connection mid-query? What am I doing wrong here? Here's my code:

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);

        }

    }

1条回答
\"骚年 ilove
2楼-- · 2019-08-02 07:29

One thing that you are doing wrong is continuing to execute doInBackground after an error that makes it impossible to continue meaningfully. For instance:

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();
}

If this throws an exception, response is going to be null and there's no point in proceeding further. You'll generate a NullPointerException in the next block of code. That won't be fatal, because you are catching all exceptions there. Further on, though, this pattern repeats and you aren't catching all exceptions.

You should exit prematurely, returning null as the String result. Then you can test for a null in onPostExecute and let the user know what happened in a graceful way.

查看更多
登录 后发表回答