java - 列表总是给出空值,直到数据被硬编码
问题描述
我有一个全局变量:
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"]}
解决方案
您可能会IndexOutOfBoundsException
因为您试图ArrayList
在 1index
而不是 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();
}
推荐阅读
- r - 如何在向量列表中分离粘贴
- .net - 即使未真正添加附件,Outlook 附件删除事件也会触发
- php - 如何为现有的 Wordpress 创建本地开发环境?
- php - 将下拉值插入数据库
- python - 即使经过大量检查和重新映射,if/else 语句也没有运行嵌入式代码
- php - 徽标的架构标记 [application/ld+json]
- r - 如何在R中按字母顺序对单个列进行排序?
- scroll - 水平滚动站点中的本机延迟加载 (loading="lazy")
- gcc - 我需要什么扩展才能从 VSCode 启动 gcc?
- python - 当我没有要求时,Pandas 将列的数据类型从浮点数更改为整数