How to populate a hashmap from an array
10,455
You're adding the same map to every slot of the array. Try this instead:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for (int i=0; i<13; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("left1", date[i]);
map.put("right1", name[i]);
mylist.add(map);
}
Author by
erdomester
Updated on June 22, 2022Comments
-
erdomester almost 2 years
i have two arrays (actually one, but i created two for each columns). I want to populate a hashmap with the values for a listview but all elements of the listview is the last element of the arrays:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map = new HashMap<String, String>(); for (int i=0; i<13; i++) { map.put("left1", date[i]); map.put("right1", name[i]); mylist.add(map); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, mylist, R.layout.row, new String[] {"left1", "right1"}, new int[] {R.id.left, R.id.right}); lv1.setAdapter(simpleAdapter);
Any ideas? Thanks
-
Powerlord about 13 years+1: And this is why you have to be careful where you put your variable declarations!
-
erdomester about 13 yearswhat do you mean? I tried to declare the arrays both in the oncreate method, both outside it, like String[] date = new String[13];
-
Kevin Coppock about 13 years@erdomester: In your original implementation, you have one map already created. Then, you're going through the loop and and putting differing values, but the same key every time (overwriting it, of course), which is why it ends up with the last value in the array. @Ted Hopp's method creates a new map each time the loop runs, and adds that map with the key and value to your array.
-
erdomester about 13 yearsI would have never thought of this. I like and know arrays better :) Thank you!
-
erdomester about 13 yearsBtw how can i remove the items from the listview? I have googled several topics, and there is no clear() or remove() command for the adapter even if a lot of people say so..
-
Ted Hopp about 13 yearsDid you look at the documentation for SimpleAdapter.remove()?