Java 创建JSONArray时出现NullPointerException
我正在我的应用程序中使用截击调用API。将字符串响应转换为JSONArray的调用失败,出现Java 创建JSONArray时出现NullPointerException,java,android,json,Java,Android,Json,我正在我的应用程序中使用截击调用API。将字符串响应转换为JSONArray的调用失败,出现java.lang.NullPointerException 我不明白为什么会有NullPointerException。我验证了我正在从API获得响应,因此我不应该将空字符串传递给JSONArray构造函数。这是代码片段。该异常发生在try-catch块中 String requestUrl = "https://api.trello.com/1/members/me/boards?key="+keys
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
}
字符串请求是异步执行的,因此在您调用try-catch中的方法时,变量尚未初始化,并且它会失败,出现
NullPointerException
我建议您将try catch中的代码移动到
onSuccess()
和onErrorResponse
方法。这样,在您收到服务器的响应后将调用该变量。字符串请求是异步执行的,因此在您调用try-catch中的方法时,该变量尚未初始化,并且由于出现NullPointerException
而失败
我建议您将try catch中的代码移动到
onSuccess()
和onErrorResponse
方法。这样,在您收到服务器的响应后将调用它。您在onResponse方法中初始化了copyResponse
,因此在调用onResponse(异步调用)之前它是空的
如果您尝试在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
}
}
在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
}
}
可能是您的copyResponse未初始化,它将int转到另一个线程,您将在响应时获得它,或者在错误中获得它可能是您的copyResponse未初始化,它将int转到另一个线程,您将在响应时获得它,或者在错误中获得它