有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

创建JSONArray时的java NullPointerException

我正在我的应用程序中使用截击调用一个API。将字符串响应转换为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

stacktrace是这样的:

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 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)

共 (0) 个答案