I frequently see code which involves iterating over the result of a database query, doing something with each row, and then moving on to the next row. Typical examples are as follows.
Cursor cursor = db.rawQuery(...);
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
...
cursor.moveToNext();
}
Cursor cursor = db.rawQuery(...);
for (boolean hasItem = cursor.moveToFirst();
hasItem;
hasItem = cursor.moveToNext()) {
...
}
Cursor cursor = db.rawQuery(...);
if (cursor.moveToFirst()) {
do {
...
} while (cursor.moveToNext());
}
These all seem excessively long-winded to me, each with multiple calls to Cursor
methods. Surely there must be a neater way?
Initially cursor is not on the first row show using
moveToNext()
you can iterate the cursor when record is not exist then itreturn false
,unless itreturn true
,The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).
I suggest:
I'd just like to point out a third alternative which also works if the cursor is not at the start position:
The best looking way I've found to go through a cursor is the following:
Don't forget to close the cursor afterwards
EDIT: The given solution is great if you ever need to iterate a cursor that you are not responsible for. A good example would be, if you are taking a cursor as argument in a method, and you need to scan the cursor for a given value, without having to worry for the cursor's current position.
Below could be the better way:
The above code would insure that it would go through entire iteration and won't escape first and last iteration.