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);

}catch (SQLiteException e){
    Log.v(TAG, "Exception "+e.getMessage());

Source code is available here for reference.

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: