在android中的asynctask中解析json

时间:2013-03-20 10:34:37

标签: java android json android-asynctask

我从定时器循环内的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;
}

这有什么不对吗?我认为这与我的asyntask有关,因为我的asyntask有时会运行几次......

1 个答案:

答案 0 :(得分:1)

NullPointerException抛出了JSONTokener,这让我认为您的jsonResponse对象是null。添加一个检查,你应该没问题:

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

else
    update = "response was null!";