HashMap values not being appended to ListView

為{幸葍}努か 提交于 2019-12-20 07:07:10

问题


i'm trying to retrieve data from a hashmap with multiple values for 1 key and set it to a listview,but instead of setting the values into the listview and displaying the listview,all that is displayed is the array(without the key). The code is as follows:

ListView lv = (ListView)findViewById(R.id.list);
    //hashmap of type  `HashMap<String, List<String>>`
    HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
    List<String> values = new ArrayList<String>();
    for (int i = 0; i < j; i++) {
        values.add(value1);
        values.add(value2);
        hm.put(key, values);
    }

and to retrieve the values and put in a listview

ListAdapter adapter = new SimpleAdapter(
                        MainActivitty.this,  Arrays.asList(hm),
                        R.layout.list_item, new String[] { key,
                                value1,value2},
                        new int[] { R.id.id, R.id.value1,R.id.value2 });
                // updating listview
                lv.setAdapter(adapter);

an example is where the key=1,value2=2 and value3=3,it will display the an array that looks like [2,3]. how do i get it to display the lisview and add the key too?


回答1:


SimpleAdapters Consturctor states as it's second parameter:

data: A List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row, and should include all the entries specified in "from"

but HashMap<String, List<String>> hm is a map of lists. So like List<Map<String,String>> hm would be the datatype you probably need.

Here is the edited source:

 ListView lv = (ListView)findViewById(R.id.list);
            List<Map<String,String>> mapList = new ArrayList<Map<String, String>>();
            Map<String,String> mapPerRow;
            for (int i = 0; i < rowNumbers; i++) {
                mapPerRow = new HashMap<String, String>();
                mapPerRow.put("column1", value1);
                mapPerRow.put("column2", value2);

                mapList.add(mapPerRow);
            }


            ListAdapter adapter = new SimpleAdapter(
                    MainActivitty.this,  mapList,
                    R.layout.list_item, new String[] { "column1", "colum2"},
                    new int[] { R.id.value1,R.id.value2 });
            // updating listview
            lv.setAdapter(adapter);

I don't get why you want the key in it (just add Strings to the map if you need more)?



来源:https://stackoverflow.com/questions/17261990/hashmap-values-not-being-appended-to-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!