0

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();
Talib
  • 1,134
  • 5
  • 31
  • 58

2 Answers2

2

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.

Tuxes3
  • 439
  • 2
  • 19
  • why not it is pointing to my data I am using insertId in query command, It should point it? – Talib Sep 09 '13 at 18:30
1

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!

Martin Cazares
  • 13,637
  • 10
  • 47
  • 54