javaandroidarraylisthashmapsimpleadapter

For loop of Hashmap to ArrayList is not holding the correct values. How to fix?


I have the following code which surprisingly doesn't work;

     needsInfoView = (ListView) findViewById(R.id.needsInfo);
            needsInfoList = new ArrayList<>();
            HashMap<String, String> needsInfoHashMap = new HashMap<>();

            for (int i = 0; i < 11; i++) {
                needsInfoHashMap.put("TA", needsTitleArray[i]);
                needsInfoHashMap.put("IA", needsInfoArray[i]);
                Log.e("NIMH",needsInfoHashMap.toString());
//Here, I get the perfect output - TA's value, then IA's value
                needsInfoList.add(needsInfoHashMap);
                Log.e("NIL",needsInfoList.toString());
//This is a mess - TA, IA values for 12 entries are all the same, they are the LAST entries of needsTitleArray and needsInfoArray on each ArrayList item.

                needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                        R.layout.needsinfocontent, new String[]{ "TA", "IA"},
                        new int[]{R.id.ta, R.id.ia});
                needsInfoView.setVerticalScrollBarEnabled(true);
                needsInfoView.setAdapter(needsInfoAdapter);
            }

Please see the comment below the log lines. That explains the output I receive. How do I make the ArrayList values pass to the two text fields in my ListView via the SimpleAdapter?

Thank you


Solution

  • For loop of Hashmap to ArrayList is not holding the correct values

    Because your are adding same instance HashMap in your needsInfoList

    You need to add new instance HashMap in your needsInfoList list like below code

    Also you need to set your needsInfoAdapter to your needsInfoView listview outside the loop like below code

    Try this

    needsInfoList = new ArrayList<>();
    needsInfoView = (ListView) findViewById(R.id.needsInfo);
    
      for (int i = 0; i < 11; i++) {
           HashMap<String, String> needsInfoHashMap = new HashMap<>();
           needsInfoHashMap.put("TA", needsTitleArray[i]);
           needsInfoHashMap.put("IA", needsInfoArray[i]);
           needsInfoList.add(needsInfoHashMap);
       }
       needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                    R.layout.needsinfocontent, new String[]{"TA", "IA"},
                    new int[]{R.id.ta, R.id.ia});
       needsInfoView.setVerticalScrollBarEnabled(true);
       needsInfoView.setAdapter(needsInfoAdapter);