AsyncTask的doInBackground返回一个NullPointerException异常只是有时 [英] AsyncTask doInBackground returning a nullpointerexception only sometimes

查看:211
本文介绍了AsyncTask的doInBackground返回一个NullPointerException异常只是有时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

收到此错误:

 了java.lang.RuntimeException:执行doInBackground发生错误()
在android.os.AsyncTask $ 3.done(AsyncTask.java:200)
在java.util.concurrent.FutureTask中$ Sync.innerSetException(FutureTask.java:274)
在java.util.concurrent.FutureTask.setException(FutureTask.java:125)
在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:308)
在java.util.concurrent.FutureTask.run(FutureTask.java:138)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:581)
在java.lang.Thread.run(Thread.java:1027)
显示java.lang.NullPointerException:产生的原因
在com.Wahoo.BrowseListActivity $ DownloadSite.doInBackground(BrowseListActivity.java:79)
在com.Wahoo.BrowseListActivity $ DownloadSite.doInBackground(BrowseListActivity.java:1)
在android.os.AsyncTask $ 2.call(AsyncTask.java:185)
在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:306)
... 4个

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

 私有类DownloadSite扩展的AsyncTask<字符串,整数,字符串> {
        私人的Htt presponse响应;
        在私人的InputStream;
        私人上下文的背景下;
        私人字符串HTML;
        私人ProgressDialog进展情况;
        @覆盖
        保护字符串doInBackground(字符串... PARAMS){            在= NULL;            字符串URL =aURLGOESHERE_BUTI'MCENSORING+参数[0] +;            HttpClient的客户端=新DefaultHttpClient();
            HTTPGET请求=新HTTPGET(URL);
            HTT presponse响应= NULL;            尝试{
                响应= client.execute(请求);
            }赶上(ClientProtocolException E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }赶上(IOException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }            尝试{
                在= response.getEntity()的getContent()。
            }赶上(IllegalStateException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(例外五){                e.printStackTrace();            }
            HTML = NULL;            读者的BufferedReader = NULL;
            尝试{
                读者=新的BufferedReader(新的InputStreamReader(中));
            }赶上(例外五){                this.publishProgress();
                this.cancel(真);                e.printStackTrace();
            }            StringBuilder的海峡=新的StringBuilder();
            串线= NULL;            尝试{
                而((行= reader.readLine())!= NULL){
                    str.append(线);
                }
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }
            尝试{
                附寄();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }
            的HTML =参数[0] + str.toString();            返回HTML;        }        @覆盖
        在preExecute保护无效(){            进度=新ProgressDialog(BrowseListActivity.this);
            progress.setIndeterminate(真);
            progress.setMessage(正在加载...);
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.show();
        }        @覆盖
        保护无效onProgressUpdate(整数...进度){            CharSequence的文字=连接中断......请重试;
            INT持续时间= Toast.LENGTH_LONG;
            吐司面包= Toast.makeText(getApplicationContext(),文本,
                    持续时间);
            toast.show();
        }        @覆盖
        保护无效onPostExecute(字符串HTML){
            progress.dismiss();            上下文的背景下= BrowseListActivity.this;
            意图stopViewer =新意图(背景下,StopActivity.class);
            stopViewer.setData(Uri.parse(HTML +));
            context.startActivity(stopViewer);        }    }


解决方案

一件事,你做错了继续,使得它不可能错误后执行 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.

这篇关于AsyncTask的doInBackground返回一个NullPointerException异常只是有时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆