How do you iterate over a cursor in reverse order
Asked Answered
A

2

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?

Audiometer answered 17/10, 2014 at 8:2 Comment(0)
A
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();
Audiometer answered 17/10, 2014 at 8:2 Comment(1)
2nd option is good, but will not work if you are limiting the number of rows to the last x. In which case option 1 is great.Tafia
B
8

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

cursor.moveToLast();
do
{
    // Stuff
}
while (cursor.moveToPrevious());
Barram answered 20/12, 2015 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.