Lilu Patel
Lilu Patel

Reputation: 321

Android Listview displays last element in the ArrayList

Hi my code only shows the last element of the ArrayList! Heres my code:

    ListView list = (ListView) findViewById(R.id.t1player_statsList);

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    HashMap<String, String> map = new HashMap<String, String>();

    for(Player player : team1.getPlayers())
        map.put("player", player.getName()); 
        map.put("score", "0");
        mylist.add(map);


    SimpleAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.mylistrow,
                new String[] {"player", "score"}, new int[] {R.id.NameCell, R.id.ScoreCell});
    list.setAdapter(mSchedule);

i feel that its something to do with my for loop. can someone please help!! thanks in advance!

Upvotes: 1

Views: 1220

Answers (1)

Lalit Poptani
Lalit Poptani

Reputation: 67296

You are creating only one instance of Hashmap that is over-writing all the values again and again and the last value remains. So, create a new instance inside for loop.

    HashMap<String, String> map;

    for(Player player : team1.getPlayers()){
        map = new HashMap<String, String>();
        map.put("player", player.getName()); 
        map.put("score", "0");
        mylist.add(map);
     }

Upvotes: 6

Related Questions