如何使用Cursor获取所有主键值并将其添加到Arraylist中?

时间:2011-09-17 06:39:12

标签: android

CREATE TABLE IF NOT EXISTS tableName _id integer primary key autoincrement,Title varchar,Description varchar。

我的表名是这样的。

请有人帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

我建议稍微解释一下这个问题,但我相信你所寻找的是一种迭代游标并获取所有主键的方法。尝试这样的事情:

ArrayList<Long> ids = new ArrayList<Long>();

if (cursor != null && cursor.getCount() > 0) {
    cursor.moveToFirst();
    do {
        long id = cursor.getLong(cursor.getColumnIndex(KEY_ROWID));
        ids.add(id);
    } while (cursor.moveToNext());
}

答案 1 :(得分:0)

让我们试试下面的代码,         如果假设表有两列_id和name,则查询Select语句时我们知道结果查询的columnindex。

 ArrayList<Integer> keyid = new ArrayList<Integer>();
           ArrayList<String> names= new ArrayList<String>();
           int id= 0;
           String name = null
        String statement = "Select * from  " + TABLE_NAME;
        Cursor c = db.rawQuery(statement, null);
        if (c.moveToFirst()) {
                do {
                             id = c.getInt(0);
                     name= c.getString(1);

                             keyid.add(id);
                             names.add(name);
                    } while (c.moveToNext());
        }
        c.close();