将可变数量的数组添加到新的String数组中

时间:2013-08-02 01:34:22

标签: android arrays expandablelistview

我正在android中创建一个expandablelistview。我有一个sql数据库,每个项目都有一个“组名”(其中有许多项具有相同的组名),然后是一个唯一的“文件名”,它分别成为我的expandablelistview和我的孩子们的组。 / p>

我想尝试创建一个可运行的expandablelistview,并根据代码添加所需的组和子项,这样我就可以将新组和新文件添加到现有组中,而且不需要重新编码。

这是我到目前为止所做的:

String[] groups;
arraylist = new ArrayList<String>();

Cursor listCursor = database.query(true, TABLE_NAME, new String[]{"groupname"}, null, null, "groupname", null, null, null);
listCursor.moveToFirst();
if (!listCursor.isAfterLast()) {
do {
    nametoadd = listCursor.getString(0);
    arraylist.add(nametoadd);
    } while (listCursor.moveToNext());
}
listCursor.close();
groups = arraylist.toArray(new String[arraylist.size()]);

正如您所看到的,它创建了一个Cursor查询,该查询在groupname列中查找不同的值,然后将每个值添加到arraylist中。然后组添加arraylist并且正常工作,我可以获得可变数量的组。我在添加孩子方面遇到了麻烦。

我现有的代码以下列方式添加子代:

private String[][] children = {
            { "child item1", "child item2", "child item3" },
            { "child item1", "child item2", "child item3" } 
};   

这里的问题是,首先,我将在每个数组中有可变数量的项目,第二,我将在children数组中有可变数量的数组。

我有第一部分的解决方案:

for (int i = 0; i < arraylist.size(); i++) {
        listCursor = database.query(TABLE_NAME, new String[]{"groupname", "description"}, "groupname='"+arraylist.get(i)+"'", null, null, null, null);
        listCursor.moveToFirst();
        if (!listCursor.isAfterLast()) {
            do {
                nametoadd = listCursor.getString(1);
                arraylist.add(nametoadd);
            } while (listCursor.moveToNext());
        }
        listCursor.close();
        childrenlist = arraylist.toArray(new String[arraylist.size()]);

    }

这会添加每个组名中的子项。但是,我如何将每个数组添加到子数组?

2 个答案:

答案 0 :(得分:0)

为孩子们创建一个班级。说

 Class Children{
     public ArrayList<String> content;
  }

答案 1 :(得分:0)

好的找到了一个有效的解决方案:

我创建了:

private List<String[]> childList;

然后补充说:

childList.add(childrenlist);

在第二个循环中。

最终代码是:

arraylist = new ArrayList<String>();

Cursor listCursor = database.query(true, TABLE_NAME, new String[]{"groupname"}, null, null, "groupname", null, null, null);
listCursor.moveToFirst();
if (!listCursor.isAfterLast()) {
    do {
    nametoadd = listCursor.getString(0);
    arraylist.add(nametoadd);
} while (listCursor.moveToNext());
}
listCursor.close();
groups = arraylist.toArray(new String[arraylist.size()]);

arraylist1 = new ArrayList<String>();
childList = new ArrayList<String[]>();
for (int i = 0; i < arraylist.size(); i++) {
listCursor = database.query(TABLE_NAME, new String[]{"groupname", "description"}, "groupname='"+arraylist.get(i)+"'", null, null, null, null);
listCursor.moveToFirst();
if (!listCursor.isAfterLast()) {
    do {
    nametoadd = listCursor.getString(1);
    arraylist1.add(nametoadd);
    } while (listCursor.moveToNext());
}
listCursor.close();
childrenlist = arraylist1.toArray(new String[arraylist1.size()]);       
childList.add(childrenlist);
arraylist1.clear();
}

然后我可以通过以下方式引用子列表中的项目:

childList.get(groupPosition)[childPosition]