gpt4 book ai didi

java - Hashmap 到 ArrayList 的 For 循环未保存正确的值。怎么修?

转载 作者:行者123 更新时间:2023-12-02 11:50:31 26 4
gpt4 key购买 nike

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

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

谢谢

最佳答案

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

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

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

此外您需要将您的needsInfoAdapter设置为循环外部的needsInfoViewlistview,如下代码

试试这个

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

关于java - Hashmap 到 ArrayList 的 For 循环未保存正确的值。怎么修?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47900959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com