Search code examples
androidsqlitedatabase-cursor

why c.moveToFirst() won't skip the first row


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

Solution

  • 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
    }