Talib
Talib

Reputation: 1164

SQLitedatabase function of moveToFirst

I have inserted some values in database and queried a cursor using the insertId for data set which I got from the database.insert command but I am not getting what is the function of cursor.moveToFirst(), Why I have to call it ? and after calling it I am able to get the inserted values in some object !!

 long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null,
        values);

   Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,
        allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
 Message newMessage = cursorToMessage(cursor);
    cursor.close();

Upvotes: 0

Views: 193

Answers (2)

Martin Cazares
Martin Cazares

Reputation: 13705

This is one way to iterate through all the possible values that a cursor might content each step is being explained:

Cursor cursor = //Reference to whatever cursor you have...
        if(cursor != null && !cursor.isAfterLast() && !cursor.isClosed()){
                //this method positions the cursor always in the first item, since there's not warranty is pointing to it...
            cursor.moveToFirst();
            do{
                //Here you have the chance to create your transfer data object and populat it with the column values...
                String column = cursor.getString(cursor.getColumnIndex("columnName"));
            }
                //Here we go to the next element in cursor IF any...
            while(cursor.moveToNext());
            cursor.close();
        }

Hope this helps.

Regards!

Upvotes: 1

Tuxes3
Tuxes3

Reputation: 447

a cursor points to your data. At first it points nowhere, so thats why you have to call moveToFirst(). If you would get more than one result you could call moveToNext() in a while loop and as long as there are results the loop goes on.

Upvotes: 2

Related Questions