Cursor skips first element

Using Android I ran into a problem with the SQL lite/SQLite examples I have found on the internet. It appeared that my cursor was skipping the first element when running a for loop.

Cursor cursor = mDataBase.rawQuery(sql, null);

for (cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast())
   //Logic Here

With a closer look I find that the cursor.moveToNext() is being evaluated before the first item. Which obviously happens because it is the do while part of the loop.

Such a simple mistake but examples all over the net are using it. Hope this helps.

The better way to do this in my opinion is as follows:

for (cursor.moveToPosition(-1); cursor.moveToNext();) {

This will loop the cursor and not skip records!


Post a Comment

Note: Only a member of this blog may post a comment.