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);
}
Share:
10,455
erdomester
Author by

erdomester

Updated on June 22, 2022

Comments

  • erdomester
    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
    Powerlord about 13 years
    +1: And this is why you have to be careful where you put your variable declarations!
  • erdomester
    erdomester about 13 years
    what 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
    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
    erdomester about 13 years
    I would have never thought of this. I like and know arrays better :) Thank you!
  • erdomester
    erdomester about 13 years
    Btw 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
    Ted Hopp about 13 years
    Did you look at the documentation for SimpleAdapter.remove()?