Home » Android » java – Cursor.moveToNext without moveToFirst

java – Cursor.moveToNext without moveToFirst

Posted by: admin June 15, 2020 Leave a comment


Will the next code work as expected?

Cursor c = db.query(tableName, requestedColumns, condition,
        conditionParams, null, null, sortOrder);
while(c.moveToNext())   {
     //do stuff with rows

The examples I found so far suggest calling c.moveToFirst() prior looping, but is it really necessary?

How to&Answers:

Yes, it will work, moveToNext actually call moveToFirst


Yes, it will work, the first moveToNext() will point the cursor to the first entry of the result set, (if the result set has values)


A late answer, but maybe useful to others finding this page. I’ve been using an: “if () do { } while();” loop. The “moveToFirst()” function returns false if no rows were returned in the cursor. The “moveToNext()” function returns false when past end of the cursor:

Cursor c = db.query(......);

if (c.moveToFirst()) do {
   data = c.getString(0) // eg. get value from first column in cursor
   // do something more
} while (c.moveToNext());