Nebula Shade
Nebula Shade

Reputation: 77

Grouping data from JSON and display on a list

I have a JSON data like this:

{
  "items": [
    {
      "kodeHp": "C-1",
      "firstName": "iman",
      "lastName": "firmansyah",
      "email": "[email protected]"
    },
    {
      "kodeHp": "C-2",
      "firstName": "dini",
      "lastName": "yyyy",
      "email": "[email protected]"
    },
    {
      "kodeHp": "C-1",
      "firstName": "tanu",
      "lastName": "xxxxx",
      "email": "[email protected]"
    },

I want to display the "firstName" on a list but sorted by the "kodeHp" object. So my list gonna looks like this:

{
iman: C1
tanu: C1
dini: C2
}

This is what I have tried:

private String parseItems(String jsonResponse) {
        ArrayList<HashMap<String,String>> list = new ArrayList<>();

        try {
            JSONObject jObj = new JSONObject(jsonResponse);
            JSONArray jArray = jObj.getJSONArray("items"); //edited on gscript

            for(int i = 0; i < jArray.length(); i++){
                JSONObject jo = jArray.getJSONObject(i);
                String kodeHp = jo.getString("kodeHp");
                String firstName = jo.getString("firstName");
                String lastName = jo.getString("lastName");
                String email = jo.getString("email");

                HashMap<String, String> item = new HashMap<>();
                if (!item.containsKey(kodeHp)){
                    item.get(kodeHp);
                }
                item.put("firstName", firstName);
                item.put("lastName", lastName);
                item.put("email",email);
                item.put("kodeHp", kodeHp);
                list.add(item);

            }
        } catch (JSONException e){

        }
        adapter = new SimpleAdapter(this, list, R.layout.item_list_row,
                new String[]{"firstName", "kodeHp"}, new int[] {R.id.TvFirstName,R.id.TvKodeHp});

        listView.setAdapter(adapter);
        loading.dismiss();
        return jsonResponse;
    }

It works to display my JSON data but not yet sorted like I want. Any suggestion?

Upvotes: 0

Views: 298

Answers (1)

Hulk
Hulk

Reputation: 6573

To sort your list, you can use List.sort with an appropriate Comparator, for example using Comparator.comparing:

list.sort(Comparator.comparing(map -> map.get("kodeHp")));

Note that this will sort alphabetically by the values of "kodeHp". Also note that you will have to add handling for null values if they are possible in you input data.


In case you need a pre-Java8 solution, e.g. for old Android versions, you'll have to create an old-fashioned anonymous class instead, for example:

list.sort(new Comparator<Map<String,String>>() {
    @Override
    public int compare(Map<String,String> o1, Map<String,String> o2) {
        return o1.get("kodeHp").compareTo(o2.get("kodeHp"));
    }
});

Upvotes: 2

Related Questions