遍历Sqlite-query中的行

kak*_*a47 50 sqlite android cursor

我有一个表格布局,我想用数据库查询的结果填充.我使用select all并且查询返回四行数据.

我使用此代码填充表行内的textviews.

Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, 
         R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);
Run Code Online (Sandbox Code Playgroud)

我希望能够分离KEY_ALT的四个不同值,并选择它们的去向.我希望他们在上面的示例中填充四个不同的textview而不是一个.如何迭代生成的游标?

此致,AK

hap*_*ude 110

Cursor数据库查询返回的对象位于第一个条目之前,因此迭代可以简化为:

while (cursor.moveToNext()) {
    // Extract data.
}
Run Code Online (Sandbox Code Playgroud)

参考来自SQLiteDatabase.

  • +1此外,`cursor.moveToPosition(-1)`将处理共享游标. (5认同)

chi*_*dev 81

您可以使用下面的代码来浏览光标并将它们存储在字符串数组中,然后在四个textview中设置它们

String array[] = new String[cursor.getCount()];
i = 0;

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    array[i] = cursor.getString(0);
    i++;
    cursor.moveToNext();
}
Run Code Online (Sandbox Code Playgroud)


Juo*_*nis 29

for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
    // use cursor to work with current item
}
Run Code Online (Sandbox Code Playgroud)


chi*_*jib 20

迭代可以通过以下方式完成:

Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
    if (cur.moveToFirst()) {
        do {
            temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table                 
        } while (cur.moveToNext());
    }
}
Run Code Online (Sandbox Code Playgroud)