我正在我的应用程序中使用 Volley 调用 API。将 String 响应转换为 JSONArray 的调用失败,并显示 java.lang.NullPointerException
。
我不明白为什么会出现NullPointerException。我验证了我正在从 API 获得响应,因此我不应该将空字符串传递给 JSONArray 构造函数。这是代码 fragment 。异常发生在try-catch block 中。
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)
最佳答案
字符串请求是异步执行的,因此当您调用 try - catch 中的方法时,变量尚未初始化,并且会失败并出现 NullPointerException
。
我建议您将 try catch 中的代码移至 onSuccess()
和 onErrorResponse
方法。这样在收到服务器的响应后就会调用它。
关于java - 创建 JSONArray 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040295/