How do you iterate over the cursor in reverse order
Usually, when I iterate over the cursor, I use something like the following:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate over an Android Cursor? has an enjoyable discussion of the various options. But now I need to go back from the first to the first cursor.
So what can I do?
+3
source to share
2 answers
There are at least two options.
First, to specifically answer your question about iterating backwards on a cursor, you can do the following:
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
// get stuff from the cursor
}
Second, you can fill the cursor in reverse order from sql and then move the cursor in the usual 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();
+7
source to share