5

Usually when I iterate over a cursor I use something like the following:

while (cursor.moveToNext()) {
    // get stuff from the cursor    
}

What's the best way to iterate an Android Cursor? has a nice discussion of the various options. But now I need to go backwards from last to first over the cursor.

So what can I do?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

8

There are at least two options.

First, to specifically answer your question about iterating backwards over the cursor, you could do the following:

for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
    // get stuff from the cursor 
}

Second, you could populate the cursor in reverse order from sql and then iterate over the cursor in your normal way:

SQLiteDatabase db = myHelper.getWritableDatabase();
String[] columns = { MyDatabaseHelper.TEST_DATE, MyDatabaseHelper.SCORE };
String orderBy = MyDatabaseHelper.TEST_DATE + " DESC"; // This line reverses the order
Cursor cursor = db.query(MyDatabaseHelper.TESTS_TABLE_NAME, columns,
        null, null, null, null, orderBy, null);

while (cursor.moveToNext()) {
    // get stuff from the cursor
}

cursor.close();
db.close();
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
8

You can start the cursor in the last position, and use moveToPrevious() until you've finished.

cursor.moveToLast();
do
{
    // Stuff
}
while (cursor.moveToPrevious());
Xebozone
  • 470
  • 6
  • 17