我从计时器服务内的android服务中的Web获取json来源的信息。有时,大约有5%的时间出现此错误:

03-20 09:27:06.901: E/AndroidRuntime(401): FATAL EXCEPTION: main
03-20 09:27:06.901: E/AndroidRuntime(401): java.lang.NullPointerException
03-20 09:27:06.901: E/AndroidRuntime(401):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:112)
03-20 09:27:06.901: E/AndroidRuntime(401):  at org.json.JSONTokener.nextValue(JSONTokener.java:90)
03-20 09:27:06.901: E/AndroidRuntime(401):  at org.json.JSONObject.<init>(JSONObject.java:154)
03-20 09:27:06.901: E/AndroidRuntime(401):  at org.json.JSONObject.<init>(JSONObject.java:171)
03-20 09:27:06.901: E/AndroidRuntime(401):  at Dic.proj.pkg.notifService.parse_if_update(notifService.java:182)
03-20 09:27:06.901: E/AndroidRuntime(401):  at Dic.proj.pkg.notifService$1$1$1.onPostExecute(notifService.java:151)
03-20 09:27:06.901: E/AndroidRuntime(401):  at Dic.proj.pkg.notifService$1$1$1.onPostExecute(notifService.java:1)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.os.AsyncTask.finish(AsyncTask.java:417)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.os.Looper.loop(Looper.java:123)
03-20 09:27:06.901: E/AndroidRuntime(401):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-20 09:27:06.901: E/AndroidRuntime(401):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 09:27:06.901: E/AndroidRuntime(401):  at java.lang.reflect.Method.invoke(Method.java:521)
03-20 09:27:06.901: E/AndroidRuntime(401):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-20 09:27:06.901: E/AndroidRuntime(401):  at    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-20 09:27:06.901: E/AndroidRuntime(401):  at dalvik.system.NativeStart.main(Native Method)


我使用RestClient libraryfot解析json。这是我的parse_if_update Asyntask:

public static String parse_if_update(String jsonResponse) {
    String update = "";
    try {
        JSONObject json = new JSONObject(jsonResponse);
        update = json.getString("update");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return update;
}


这怎么了?我认为这与我的异步任务有关,因为有时我的异步任务会运行几次...

最佳答案

NullPointerExceptionJSONTokener引发,这使我认为您的jsonResponse对象是null。为此添加一张支票,您应该可以:

if (jsonResponse != null) {
    JSONObject json = new JSONObject(jsonResponse);
    update = json.getString("update");
}

else
    update = "response was null!";

10-07 12:56