gpt4 book ai didi

android - 如何在将 ArrayList 添加到 Android 中的 HashMap 后清除 ArrayList?

转载 作者:行者123 更新时间:2023-11-29 17:47:31 25 4
gpt4 key购买 nike

我正在做一个小的 Android 应用程序。因为我有 Expandable listview 并试图从 SQLite 中填充数据。 所以我使用 HashMap 来存储 parent(String) child(ArrayList)

例如,我在 parent(1, 2, 3, 4) 中有四个整数编号,我得到它并存储在 ListArray 中。现在我需要为那个特定的 parent 获得 child (ListArray)。 Parent 1 contain (aa, bb), parent 2 contain (cc)..等等,现在看这段代码

try 
{
header = new ArrayList<String>();
footer = new ArrayList<String>();
child= new HashMap<String, List<String>>();
String date = null;

int count=0, countchild=0;
Cursor c = db.rawQuery("SELECT Date FROM Table", null);
if (c.moveToFirst())
{
do
{
date=c.getString(c.getColumnIndex("Date"));
header.add(date);
count=count+1;

} while (c.moveToNext());
}

for (int i = 0; i < count; i++)
{
String temp=header.get(i);
Cursor cc=db.rawQuery("SELECT Id FROM Table WHERE Date ='"+ temp +"' ", null);
if(cc.moveToFirst())
{
do
{
countchild=countchild+1;
String id=cc.getString(cc.getColumnIndex("Id"));
//footer.clear(); // it clear all data's on child
footer.add(id);
Log.d("Footer date count", "" + countchild);
child.put(temp, footer);
}
while (cc.moveToNext());

//footer.clear(); // it clear all data's on child
}
footer.clear(); // it clear all data's on child
}

}

我想在将 footer 添加到 child 之后清除这里的 footer,这样我才能获得正确的 Expandable listview。如果我删除/评论此 footer.clear() 行,则所有 child 的都将添加到所有 parent 。 例如,父级 1 包含(aa、bb、cc 等),父级 2 包含(aa、bb、cc 等)。如果我离开此 footer.clear() 行,则所有子项都将被清除并仅显示这样的父项,例如 Parent 1()、Parent 2()... 等

如何在将 footer(ListArray) 添加到 HashMap 后清除它??或者告诉我一些修改此代码的建议。

谢谢。斯里哈里

最佳答案

当您将ArrayList放入HashMap时,HashMap实际上保存了对数组的引用,不是副本。

这就是为什么你必须为每个组使用不同的数组:

for (int i = 0; i < count; i++)
{
List<String> children = new ArrayList<String>();
String temp = header.get(i);
Cursor cc = db.rawQuery("SELECT Id FROM Table WHERE Date ='"+ temp +"' ", null);
if(cc.moveToFirst())
{
countChild += cc.getCount();
Log.d("Footer date count", "" + countchild);
do
{
String id = cc.getString(cc.getColumnIndex("Id"));
children.add(id);
child.put(temp, children);
}
while (cc.moveToNext());
}
}

如您所见,这里为每个组创建了一个新的 children ArrayList 并且它永远不会被清除,因为那样会清除来自HashMap也是。

此外,我让自己修复了一些其他问题,例如使用 CursorgetCount 方法来获取计数而不是循环。此外,我没有使用 footer 数组,因为它在您显示的代码中是不必要的。

最后,请为您的变量使用易于理解且有意义的名称,因为它可以帮助您以及阅读您代码的其他人。

关于android - 如何在将 ArrayList 添加到 Android 中的 HashMap 后清除 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462745/

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