使用游标获取字段值

33

我正在创建一个应用程序,但在使用 Cursor 时遇到了问题。我有一个 SQLiteDatabase,当我尝试使用这个函数获取值时,它会返回一个 Cursor

public Cursor fetchOption(long rowId) throws SQLException {

    Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
        KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
        null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

我不知道如何获取Cursor中字段的值。如果我这样做:

String a = mOptionDb.fetchOption(0).getColumnName(0).toString();
String b = mOptionDb.fetchOption(0).getColumnName(1).toString();
String c = mOptionDb.fetchOption(0).getColumnName(2).toString();

我只获得列名(_id, title, body)而没有值。有什么建议可以实现这一点吗?

3个回答

94

我认为你可以忽略检查 null。

相反,检查是否有数据,然后使用游标访问列:

Cursor cursor = fetchOption(0);

if (cursor.moveToFirst()) // data?
   System.out.println(cursor.getString(cursor.getColumnIndex("title")); 

cursor.close(); // that's important too, otherwise you're gonna leak cursors

阅读 Android 教程可能也是有意义的。记事本教程似乎符合要求:http://developer.android.com/guide/tutorials/notepad/index.html


2
谢谢你的帮助。现在它可以工作了。我忘记了每次访问都要关闭游标... - Michaël
1
每次我遇到这个问题,我都会回到这里并意识到我忘记了cursor.moveToFirst()。谢谢! - user1549672

17
您可以使用 Cursorget* 方法从结果中检索值:
long id = cursor.getLong(cursor.getColumnIndex("_id"));
long title = cursor.getString(cursor.getColumnIndex("title"));
...

显然更好的做法是使用常量(通常由ContentProviders提供),而不是使用硬编码字符串调用getColumnIndex


使用以下代码: int a = mOptionDb.fetchOption(0).getColumnIndex("title"); 我得到了“1”。 但是,当我使用mOptionDb.fetchOption(0).getString(a)时,出现了错误: ERROR/AndroidRuntime(628): Uncaught handler: thread main exiting due to uncaught exception ERROR/AndroidRuntime(628): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 就像没有数据一样! - Michaël

7
您可以使用这种机制。
Cursor record=db.test(finalDate);     
if(record.getCount()!=0){
    if(record.moveToFirst()){
        do{               
            Imgid1=record.getString(record.getColumnIndex(Database.PHOTO));                
        }while(record.moveToNext());                          
    } 
    record.close();        
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接