用新项填充数组(android-section-list)

时间:2013-12-05 19:06:02

标签: android arrays listview arraylist add

我在"android-section-list"项目中有这个例子:

SectionListItem[] exampleArray = {
            new SectionListItem("Test 1 - A", "A"), 
            new SectionListItem("Test 2 - A", "A"),
            new SectionListItem("Test 3 - A", "A"),
            new SectionListItem("Test 4 - A", "A"),
            new SectionListItem("Test 5 - A", "A"),
            new SectionListItem("Test 6 - B", "B"),
            new SectionListItem("Test 7 - B", "B"),
            new SectionListItem("Test 8 - B", "B"),
            new SectionListItem("Test 9 - Long", "Long section"),
            new SectionListItem("Test 10 - Long", "Long section"),
            new SectionListItem("Test 11 - Long", "Long section"),
            new SectionListItem("Test 12 - Long", "Long section"),
            new SectionListItem("Test 13 - Long", "Long section"),
            new SectionListItem("Test 14 - A again", "A"),
            new SectionListItem("Test 15 - A again", "A"),
            new SectionListItem("Test 16 - A again", "A"),
            new SectionListItem("Test 17 - B again", "B"),
            new SectionListItem("Test 18 - B again", "B"),
            new SectionListItem("Test 19 - B again", "B"),
            new SectionListItem("Test 20 - B again", "B"),
            new SectionListItem("Test 21 - B again", "B"),
            new SectionListItem("Test 22 - B again", "B"),
            new SectionListItem("Test 23 - C", "C"),
            new SectionListItem("Test 24 - C", "C"),
            new SectionListItem("Test 25 - C", "C"),
            new SectionListItem("Test 26 - C", "C"),
    };

但我必须以编程方式从数据库中填充数组项。 以下只是为了说明我认为结果应该是什么。 我知道语法是完全错误的,但我认为你现在对我想要的内容是什么意思:

Cursor mCursor = mDbHelper.getChecklistAllByTitle();
    // looping through all entries and adding to list
    if (mCursor.moveToFirst()) {
        SectionListItem[] exampleArray = {
        do {
            new SectionListItem(mCursor.getString(1),mCursor.getString(2));
            }while (mCursor.moveToNext());
        +};
    }
    mCursor.close();

正如我所说的那样,代码自然是错的......我知道......但是没有解决方案:-( 如何通过迭代数据库条目来正确填充数组呢?

1 个答案:

答案 0 :(得分:1)

正如您毫无疑问地注意到的那样,本机数组不是动态的,在您查看数据库中的所有数据之前,您不知道需要多少条目。所以从一个ArrayList开始,而不是像你需要的那样增长:

ArrayList<SectionListItem> my_list = new ArrayList<SectionListItem>();

然后遍历游标,随时添加到ArrayList:

while (mCursor.moveToNext())
{
    my_list.add(new SectionListItem(mCursor.getString(1),mCursor.getString(2));
}
cursor.close();

然后,您可以使用toArray方法将ArrayList转换为本机数组:

SectionListItem[] exampleArray = my_list.toArray(new SectionListItem[my_list.size()];
相关问题