我有以下代码令人惊讶地无法正常工作;
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中的两个文本字段?
谢谢
答案 0 :(得分:1)
对于
Hashmap
到ArrayList
的循环没有保持正确的值
因为您在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);
....
}