使用Async任务时,Android空指针异常

时间:2013-04-25 13:22:15

标签: android json

我的课程中有一个异步任务,它是关于解析JSON的。但是当我执行代码时,在LogCat中我看到了消息:FATAL EXCEPTION:AsyncTask#1

引起:java.lang.NullPointerException。

如果你想看一下,这是我的代码:

MainActivity.java

    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         new ReadJSON().execute(there is an address here);

         textView = (TextView) findViewById(R.id.textView1);
   }

   //async task:
    InputStream inputStream = null;
    String result = null;
    HttpResponse response;
    BufferedReader reader;
    JSONObject jObject;
    String aJsonString1;
    String aJsonString2;


    public class ReadJSON extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... url) {

            DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost(there is the same address here);
            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            try {
                response = httpclient.execute(httppost);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
            HttpEntity entity = response.getEntity();

            try {
                inputStream = entity.getContent();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // json is UTF-8 by default i beleive

            try {
                reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            result = sb.toString();



            try {
                jObject = new JSONObject(result);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                aJsonString1 = jObject.getString("value");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                aJsonString2 = jObject.getString("timestamp");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return aJsonString1;

        }

            protected void onPostExecute(String result) {
                textView.setText(aJsonString1);


            }

    }  

你能在这里看到问题吗?有人有想法吗?

提前致谢

编辑:这是LogCat:

   04-25 16:27:06.851: W/System.err(4697):  at     android.os.AsyncTask$2.call(AsyncTask.java:287)
   04-25 16:27:06.861: W/System.err(4697):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
   04-25 16:27:06.861: W/System.err(4697):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
   04-25 16:27:06.871: W/System.err(4697):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
   04-25 16:27:06.871: W/System.err(4697):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
   04-25 16:27:06.881: W/System.err(4697):  at java.lang.Thread.run(Thread.java:856)
   04-25 16:27:06.891: W/dalvikvm(4697): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
   04-25 16:27:06.911: E/AndroidRuntime(4697): FATAL EXCEPTION: AsyncTask #1
   04-25 16:27:06.911: E/AndroidRuntime(4697): java.lang.RuntimeException: An error occured while executing doInBackground()
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.lang.Thread.run(Thread.java:856)
   04-25 16:27:06.911: E/AndroidRuntime(4697): Caused by: java.lang.NullPointerException
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at com.example.ayasms.MainActivity$ReadJSON.doInBackground(MainActivity.java:189)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at com.example.ayasms.MainActivity$ReadJSON.doInBackground(MainActivity.java:1)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
   04-25 16:27:06.911: E/AndroidRuntime(4697):  ... 4 more 

2 个答案:

答案 0 :(得分:2)

我假设您在AsyncJob中尝试捕获错误处理是个问题。

例如,如果行httpclient.execute(httppost);抛出异常,则将其捕获并打印到Stderr(在LogCat中部分可见),然后继续!

当然没有执行httpclient.execute(..)你没有响应,因此你得到一个NullPointerException。

结论:在一个try catch环境中将所有内容打包在AsyncJob中。此外,您应该首先调查哪个类失败并找出原因。

try {
    response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    inputStream = entity.getContent();
    reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
    result = sb.toString();
    jObject = new JSONObject(result);  
    aJsonString1 = jObject.getString("value");
    aJsonString2 = jObject.getString("timestamp");
    return aJsonString1;
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();  
} catch (JSONException e) {
    e.printStackTrace();
}           
return null; // Error case

答案 1 :(得分:1)

在这一行:

textView.setText(aJsonString1);

textView可能仍为空。

因此,在您的onCreate方法中切换以下行:

new ReadJSON().execute(there is an address here);

textView = (TextView) findViewById(R.id.textView1);

textView = (TextView) findViewById(R.id.textView1);
new ReadJSON().execute(there is an address here);