【问题标题】:For loop of Hashmap to ArrayList is not holding the correct values. How to fix?Hashmap 到 ArrayList 的 For 循环未保存正确的值。怎么修?
【发布时间】:2018-06-02 17:08:19
【问题描述】:

我有以下代码令人惊讶地不起作用;

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

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

谢谢

【问题讨论】:

  • HashMap 是为唯一性而设计的,如果您尝试添加与 previous 相同的键,那么它将更新键值

标签: java android arraylist hashmap simpleadapter


【解决方案1】:

HashmapArrayList 的 For 循环的值不正确

因为您在 needsInfoList 中添加了相同的实例 HashMap

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

另外您需要在循环外将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);

【讨论】:

    【解决方案2】:

    您将多次向List 添加相同的HashMap 实例,这意味着您在每次迭代中放入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);
        ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2012-08-29
      • 2015-10-03
      • 1970-01-01
      • 2017-06-03
      相关资源
      最近更新 更多