33

I'm creating an application and I have problems with Cursor. I have an SQLiteDatabase that returns me a Cursor when I try to fetch the values with this function:

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;

}

I don't know how to obtain the value of the field in the Cursor. If I do that like so:

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

I only obtain the name of the columns (_id, title, body) but not the values. Any suggestions on how to achieve this?

Razor
  • 1,778
  • 4
  • 19
  • 36
Michaël
  • 3,679
  • 7
  • 39
  • 64

3 Answers3

94

I think you can forget about checking for null.

Instead check if there is data and then access the columns using the cursor:

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

It might also make sense to read an Android tutorial. The notepad tutorial seems to fit the bill: http://developer.android.com/guide/tutorials/notepad/index.html

Mariano Kamp
  • 2,366
  • 20
  • 26
17

You can use the Cursor's get* methods to retrieve values from the result:

long id = cursor.getLong(cursor.getColumnIndex("_id"));
long title = cursor.getString(cursor.getColumnIndex("title"));
...

Better practice is obviously to use constants (often provided by ContentProviders) instead of calls to getColumnIndex with hardcoded strings.

Josef Pfleger
  • 74,165
  • 16
  • 97
  • 99
  • with the part : int a = mOptionDb.fetchOption(0).getColumnIndex("title"); I obtain "1". But with mOptionDb.fetchOption(0).getString(a); I obtain errors : 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 It's like there isn't datas?! – Michaël May 24 '09 at 10:28
7

You can use this mechanism.

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();        
}
Michaël
  • 3,679
  • 7
  • 39
  • 64