首页 > 解决方案 > 列表总是给出空值,直到数据被硬编码

问题描述

我有一个全局变量: 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"]}

标签: javaandroidarraylist

解决方案


您可能会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();
    }

推荐阅读