3

I always use the code below to get all the informations
But I have question that c.movetoNext lead to skip the first row of result set
Please tell me what really happens behind the surface so that I can fully understand it

    SQLiteDatabase db;
    Cursor c = db.query("pic", null, null, null, null,null, null);
    c.moveToFirst();
    while(c.movetoNext)
    {
    //do something
    //example: String a=c.getString(0);
    }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
IloveIniesta
  • 342
  • 4
  • 20

5 Answers5

14

You're calling moveToFirst(), which positions the cursor on the first row, then your while loop calls moveToNext() before entering the loop, which results in the first row being skipped.

You can solve it with either a do...while loop, or a for loop such as

for( c.moveToFirst(); !c.isAfterLast(); c.moveToNext() ) {
    // Stuff
}
Khantahr
  • 8,156
  • 4
  • 37
  • 60
2

A late answer, but hopefully 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 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());

c.close();

(which is similar to TactMayers' answer).

1

According to the Cursor documentation, "query... Returns: A Cursor object, which is positioned before the first entry". It further seems that queries get executed only when methods are called on the cursor. Hope that helps.

Community
  • 1
  • 1
hd1
  • 33,938
  • 5
  • 80
  • 91
0
c.moveToFirst();

This line move the cursor to the first row.

while(c.movetoNext)

After running this line of code, the cursor will move to next row (row 2 for the first run of the while loop.) So by the time the code enter the loop, the cursor is pointing to row 2 already and can never access the first row.

Try replacing the while loop like this

do {
    // do something
} while(c.movetoNext())
TactMayers
  • 884
  • 8
  • 22
0

Actually, you do not have to call c.moveToFirst(); at all

Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • And why would that be? Do you have any references for that statement? – Flow Sep 08 '13 at 17:50
  • Because initial index is `-1` and `moveToNext()` on that simply means index 0, see http://androidxref.com/7.0.0_r1/xref/frameworks/base/core/java/android/database/AbstractCursor.java#257. – Baris Demiray Nov 30 '16 at 21:22