Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the field value with a Cursor

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?

like image 790
Michaël Avatar asked May 24 '09 08:05

Michaël


People also ask

What is cursor in Android with example?

This interface provides random read-write access to the result set returned by a database query. Cursor implementations are not required to be synchronized so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.


1 Answers

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

like image 106
Mariano Kamp Avatar answered Sep 23 '22 02:09

Mariano Kamp