Android:JSONArray进入ExpandableList问题

时间:2016-05-26 13:12:15

标签: android arrays json expandablelistview

我想用JSONArray创建一个可扩展的列表。 该应用程序工作但不完美。我想我的for()声明有问题。 这是代码:

listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
String json_string;

try {
    json_string = json;

    jsonObject = new JSONObject(json_string);
    jsonArray = jsonObject.getJSONArray("server_response");
    if (jsonArray.length() > 0) {
        object = jsonArray.getJSONObject(0);
        for (int i = 0; i < object.length(); i++) {
            //Check with Log.e
            Log.e(TAG, "Key = " + object.names().getString(i) + " value = " + object.get(object.names().getString(i)));
            /*** Working with ExpandableList ***/
            listDataHeader.add(object.names().getString(i));
            List<String> list = new ArrayList<>();
            list.add((object.get(object.names().getString(i))).toString());
            listDataChild.put(listDataHeader.get(i), list);
        }

        listAdapter = new ExpandableListAdapter(getContext(), listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);
    } else {
        System.out.println("Empty JSON");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

还有JSON字符串:

{
"server_response": [{
    "Medii Vizuale De Programare": "10",
    "Retele De Calculatoare": "8",
    "Tehnici Avansate De Programare": "9",
    "Tehnologii Web": "9",
    "Baza De Date": "9",
    "Programare Functionala": ""
}, {
    "Medii Vizuale De Programare": "8",
    "Retele De Calculatoare": "5",
    "Tehnici Avansate De Programare": "6",
    "Tehnologii Web": "7",
    "Baza De Date": "10",
    "Programare Functionala": "8"
}]}

所以,问题是当我想看到值时,只显示第一个对象,第二个不显示。 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

你正在循环JsonObject,你必须循环JsonArray

if (jsonArray.length() > 0) {
    for (int i = 0; i < jsonArray.length(); i++) {
        object = jsonArray.getJSONObject(i);
        Log.e(TAG, "Key = " + object.names().getString(i) + " value = " + object.get(object.names().getString(i)));
       /*** Working with ExpandableList ***/
       listDataHeader.add(object.names().getString(i));
       List<String> list = new ArrayList<>();
       list.add((object.get(object.names().getString(i))).toString());
       listDataChild.put(listDataHeader.get(i), list);
    }
    :
    :
}//if array >0