Android Basics – Learn how to Navigate a Cursor to get data

In an earlier Article you saw how to populate data, from the database, to a cursor using the query() method.

Once the Cursor has data you can iterate over it. On every iteration you can get data corresponding to a row in the table.

There are four main methods available to navigate through a Cursor:

  • moveToFirst()
  • moveToLast()
  • moveToPrevious()
  • moveToNext()

In the example below we demonstrate how to use moveToFirst() method

//Sample Code to query the database
try {
    SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
    SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

    Cursor cursor = surveyDBHelper.getSurveyData(db);

    if (cursor.moveToFirst()) {
        //Get the data
        String name = cursor.getString(1);
        String email = cursor.getString(2);
        Log.v(TAG, "Name "+name);
    }

    cursor.close();
    db.close();
}catch (SQLiteException e){
    Log.v(TAG, "Exception "+e.getMessage());
}
//End

Source code is available here for reference.

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s