我有一个全局变量:
List<String> cheifComplaintList = new ArrayList<>();
和方法:fetchCheifComplaints()
,该方法描述为:
private void fetchCheifComplaints() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
endpoints.ENDPOINT_GET_CHEIF_COMPLAINTS,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (BuildConfig.DEBUG) Log.d(TAG, "onResponseCheifComplaints: " + response);
try {
JSONArray jsonArray = response.getJSONArray("complaints");
for (int i = 1; i < jsonArray.length(); i++) {
if (BuildConfig.DEBUG) Log.d(TAG, "List: " + jsonArray.getString(i));
cheifComplaintList.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponseCheifComplaints: ", error);
}
})
但是我总是得到cheifComplaintList = null
。
但是,当我将值设置为cheifComplaintList.add("Some value");
时,它们会起作用。有人可以帮忙吗?谢谢我前进。
Json的回复是:
onResponseCheifComplaints: {"complaints":[""," Bad breath"," Bleeding gum","Senstivity"," Tooth ache","Wants to clean the teeth"]}
答案 0 :(得分:0)
您可能会收到IndexOutOfBoundsException
,因为您试图将数据插入ArrayList
的位置为1 index
而不是0 index
请参见以下代码,并在int i=0;
中输入for loop
try {
JSONArray jsonArray = response.getJSONArray("complaints");
for (int i = 0; i < jsonArray.length(); i++) {
if (BuildConfig.DEBUG) Log.d(TAG, "List: " + jsonArray.getString(i));
cheifComplaintList.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
希望这会有所帮助