对于Hashmap到ArrayList的循环没有保持正确的值。怎么修?

时间:2017-12-20 07:36:13

标签: java android arraylist hashmap simpleadapter

我有以下代码令人惊讶地无法正常工作;

     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);
            }

请参阅日志行下方的评论。这解释了我收到的输出。如何通过SimpleAdapter将ArrayList值传递给ListView中的两个文本字段?

谢谢

2 个答案:

答案 0 :(得分:1)

  

对于HashmapArrayList的循环没有保持正确的值

因为您在HashMap

中添加了相同的实例needsInfoList

您需要在HashMap列表中添加新实例needsInfoList,如下面的代码

您需要将needsInfoAdapter设置为循环外的needsInfoView listview,如下面的代码

试试这个

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);

答案 1 :(得分:0)

您正在向HashMap多次添加相同的List实例,这意味着您在每次迭代时放入Map的条目将替换上一次迭代所放置的条目。

您应该在每次迭代时创建一个新的HashMap实例:

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);
    ....
}
相关问题