复制 key 时我遇到了这个 HashMap 问题。 (安卓)
最初我有一个与此类似的 xml 文件
<many_people>
<people>
<id>1</id>
<name>Johnson</name>
<tel_num>12345678</tel_num>
</people>
.
.
.
</many_people>
所以我用 hashmap 创建了 arraylist 来存储整个 xml
for (int i = 0; i < nl.getLength(); i++) {
map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_TELNUM, parser.getValue(e, KEY_TELNUM));
// adding HashList to ArrayList
peopleList.add(map);
}
我使用 onItemClickListener 捕获来自 AutoCompleteTextView 的输入,以便我可以将输入与 xml 进行比较。 peopleList 稍后将在 listView 中使用。
例如: 输入 - 约翰逊 与 进行比较,如果找到,那么我的 ListView 将显示约翰逊的姓名和联系方式。问题就在这里,如果我有 2 个约翰逊,listView 只读取 xml 中的第一个约翰逊。 我不知道如何将输入与 xml 进行比较。 下面是我的代码:
for (HashMap<String, String> map : peopleList) {
if (input.equals(map.get(KEY_NAME))) {
// At here I created another hashmap with copying the value
map2.put(KEY_ID, map.get(KEY_ID));
map2.put(KEY_NAME, map.get(KEY_NAME));
map2.put(KEY_NAME, map.get(KEY_TELNUM));
peopleList2.add(map2);
}
}
我成功地在 ListView 中显示第一个数据,但第二个和第三个数据(与约翰逊同名)失败。我不确定这是否可行。
最佳答案
在这里:
for (HashMap<String, String> map : peopleList) {
if (input.equals(map.get(KEY_NAME))) {
// At here I created another hashmap with copying the value
map2.put(KEY_ID, map.get(KEY_ID));
map2.put(KEY_NAME, map.get(KEY_NAME));
map2.put(KEY_NAME, map.get(KEY_TELNUM));
peopleList2.add(map2);
}
}
At here I created another hashmap with copying the value
好吧,如果这就是您的整个 FOR 循环代码,那么您肯定没有创建另一个映射。您只需一遍又一遍地更新同一个 HashMap (map2
) 并将其添加到列表中。由于您使用相同的 HashMap,因此您只需一遍又一遍地更新同一对象,最后以对同一“人”的 N(匹配数)引用结束。
就像 Michael 所说,没有理由这样做,你应该创建一个 Person 类。
关于java - Android Hashmap 无法显示在 listView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014604/