Android convert JSONObject to HashMap and display in ListView with SimpleAdapter

前端 未结 2 1044
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 04:05

I try to search converting JSONObject to HashMap but most of the results are for Java not Android. Hence, I hope someone can share if you have experien

2条回答
  •  借酒劲吻你
    2021-01-24 04:46

    You could do something like this:

    ListView listView = (ListView) findViewById(R.id.listView);
    
    // ...
    
    @Override
    public void onResponse(JSONObject response) {
        List> list = new ArrayList>();
    
        try {
            Iterator iterator = response.keys();
    
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = response.getString(key);
    
                HashMap map = new HashMap<>();
                map.put(KEY_ID, key);
                map.put(KEY_NAME, value);
    
                list.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        if(list.size() > 0) {
            String[] from = {KEY_ID, KEY_NAME};
            int[] to = {R.id.text_id, R.id.text_name};
    
            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
                R.layout.list_item, from, to);
    
            listView.setAdapter(adapter);
        }
    }
    

提交回复
热议问题