Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you iterate over a cursor in reverse order

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?

like image 313
Suragch Avatar asked Oct 17 '14 08:10

Suragch


People also ask

How to iterate through a list in reverse order in Python?

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]).

How to get a list iterator over the elements in list?

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.

What order is the Dictionary iterated in?

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".

How to iterate a sequence in Python?

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.


2 Answers

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();
like image 192
Suragch Avatar answered Oct 23 '22 12:10

Suragch


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

cursor.moveToLast();
do
{
    // Stuff
}
while (cursor.moveToPrevious());
like image 41
Xebozone Avatar answered Oct 23 '22 11:10

Xebozone