I'm making a call to an API using Volley in my app. And the call to convert the String response to a JSONArray fails with a java.lang.NullPointerException
.
I don't understand why there is a NullPointerException. I verified that I'm getting a response from the API so i should not be passing a null string to the JSONArray constructor. This is the code snippet. The exception occurs in the 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
}
A sample response from the API is here: http://pastebin.com/Bs2GYPcC
The stacktrace is like so:
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)