且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AsyncTask的doInBackground返回一个NullPointerException异常只是有时

更新时间:2023-11-19 12:30:40

一件事,你做错了继续,使得它不可能错误后执行 doInBackground 继续有意义。例如:

  {尝试
    响应= client.execute(请求);
}赶上(ClientProtocolException E1){
    // TODO自动生成catch块
    e1.printStackTrace();
}赶上(IOException异常E1){
    // TODO自动生成catch块
    e1.printStackTrace();
}

如果此抛出一个异常,响应将是并有进一步继续毫无意义。您将在code的下一个块生成一个 NullPointerException异常。这不会是致命的,因为你正赶上所有异常那里。再往前,虽然,这种模式重复,你是不是捕捉所有异常。

您应该pmaturely退出$ P $,返回作为字符串结果。然后,你可以在 onPostExecute 测试一个键,让用户知道在一个优雅的方式发生了什么。

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

        }

    }

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.