创建JSONArray

时间:2015-10-09 14:02:56

标签: java android json

我正在使用我的应用中的Volley调用API。将String响应转换为JSONArray的调用失败,并带有java.lang.NullPointerException

我不明白为什么会出现NullPointerException。我验证了我从API获得响应所以我不应该将空字符串传递给JSONArray构造函数。这是代码段。 try-catch块中发生异常。

String requestUrl = "https://api.trello.com/1/members/me/boards?key="+keys.apiKeyTrello+"&token="+savedToken;

StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        boardListView.setText("Response is: " + response);
        copyResponse = new String(response);
        Log.d("timer", "reached here");
    }
},
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            copyResponse = new String("[{\"error\":\"error\"}]");
            boardListView.setText("That didn't work!");
    }
});

queue.add(stringRequest);

try {
    JSONArray jsonArray = new JSONArray(copyResponse); // NullPointerException here
}
catch (JSONException e){
    //Handle exception
}

来自API的示例回复位于:http://pastebin.com/Bs2GYPcC

堆栈跟踪是这样的:

10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: FATAL EXCEPTION: main
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: Process: im.chaitanya.pomodorotimer, PID: 3535
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{im.chaitanya.pomodorotimer/im.chaitanya.pomodorotimer.ShowBoardList}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)

2 个答案:

答案 0 :(得分:2)

String请求是异步执行的,所以当你在try-catch中调用方法时,该变量尚未初始化,并且失败并带有NullPointerException

我建议您将try catch中的代码移动到onSuccess()onErrorResponse方法。这样,它将在您收到服务器的响应后调用。

答案 1 :(得分:1)

您在onResponse方法中初始化copyResponse,因此在调用onResponse之前它是null(异步调用)。

如果你尝试在onResponse方法中解析你的JSONArray它应该工作。类似的东西:

@Override
public void onResponse(String response) {
    // Display the first 500 characters of the response string.
    boardListView.setText("Response is: " + response);
    //copyReponse is useless here. You can directly use response
    Log.d("timer", "reached here");
    try {
        JSONArray jsonArray = new JSONArray(response);
    }
    catch (JSONException e){
        //Handle exception
    }
}