Search code examples
javaandroidjsonandroid-listviewsimpleadapter

SimpleAdapter on HashMap does not work properly


I have a JSON like this:

 [{"message":"Hello","id":1,"name":"Hello"},{"message":"James","id":2,"name":"Smith"}]

Which I use to populate an ArrayList<HashMap<String, String>> in order to diplay the json's items into a ListView.
This is the code I am currently using:

   private void createListView(){
        for(int i = 0 ; i < json.length() ; i++){
            try{
                JSONObject temp = json.getJSONObject(i);
                HashMap<String, String> map = new HashMap<>();
                map.put("name", temp.getString("name"));
                map.put("message", temp.getString("message"));
                data.add(map);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        String[] from = new String[]{"name", "message"};
        int to[] = new int[]{android.R.id.text1};

        ListAdapter adapter = new SimpleAdapter(getBaseContext(), data, android.R.layout.simple_list_item_1, from, to);
        setListAdapter(adapter);
        Log.d("Debug", json.toString());

    }

This code almost work, but not the way I would. It display only the name field.

How can I modify it in order to display both the message and name field ?


Solution

  • It display only the message field.

    Because using android.R.layout.simple_list_item_1 for row which contain only on TextView with android.R.id.text1 id

    How can I modify it in order to display both the message and name field ?

    Use android.R.layout.simple_list_item_2 as layout for rows and change to array :

    int to[] = new int[]{android.R.id.text1,android.R.id.text2};