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

问题描述 投票:0回答:2

我有以下代码,令人惊讶的是不起作用;

     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中的两个文本字段?

谢谢

java android arraylist hashmap simpleadapter
2个回答
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);

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);
    ....
}
© www.soinside.com 2019 - 2024. All rights reserved.