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?
There are several ways to iterate through a list in reverse order some of them are: When it comes to iterating through something, the loop is always helpful. To iterate in Python, we use the range () function. This approach is known as range ( [start], stop [, step]).
Approach 1: Using List.listIterator () and Using for loop method. Return Value: This method returns a list iterator over the elements in this list (in proper sequence). This allows bidirectional access. List.listIterator () method is used to get a ListIterator over the elements in a list starting from specified position in the list.
The dictionary happens to be iterated in the order "a", "h", "n". I need to process "a" last because it's dependent on the files in "h" and "n".
To iterate in Python, we use the range () function. This approach is known as range ( [start], stop [, step]). start: This is the sequence’s first index.
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();
You can start the cursor in the last position, and use moveToPrevious() until you've finished.
cursor.moveToLast();
do
{
// Stuff
}
while (cursor.moveToPrevious());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With