我面临一些已知的可解决问题,但在这里被解决了。在我的代码中,值在第一次 for 循环执行时存储在 ArrayList 中。但是,在第二次循环及以后的循环中,这些值将被 ArrayList 中的最终值覆盖。最后,最后输入的值单独与列表大小的倍数一起存储。
lstall = (ListView)findViewById(R.id.lvall);
sampleArrayList = new ArrayList<HashMap<String, String>>();
ListAdapter sampleListAdapter;
dh = new DBHelper(this);
HashMap<String, String> sampleObjectMap;
List<String> lvall = dh.selectAll();
sampleObjectMap= new HashMap<String, String>();
for(int i=0;i<lvall.size();i++)
{
for (@SuppressWarnings("unused") String sampleObj : lvall)
{
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
}
sampleArrayList.add(sampleObjectMap);
}
我需要将所有值存储在数组列表中并在 ListView 中显示。非常感谢任何帮助,并提前致谢。
最佳答案
您正在创建一个 HashMap<String, String>
并反复覆盖其中的条目。
事实上,您会这样做两次,因为您没有明显的原因有一个嵌套的 for 循环。我相信你想要:
for (int i = 0; i < lvall.size(); i++)
{
HashMap<String, String> sampleObjectMap = new HashMap<String, String>();
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
sampleArrayList.add(sampleObjectMap);
}
使用列表的大小但实际上不使用列表中的值似乎也很奇怪...您可能需要考虑重组代码...
关于java - 如何解决android中的这个hashmap逻辑错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7964511/