【发布时间】:2014-10-17 08:02:14
【问题描述】:
通常当我遍历游标时,我会使用如下内容:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate an Android Cursor? 对各种选项进行了很好的讨论。但是现在我需要在光标上从最后一个倒退到第一个。
那我该怎么办?
【问题讨论】:
通常当我遍历游标时,我会使用如下内容:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate an Android Cursor? 对各种选项进行了很好的讨论。但是现在我需要在光标上从最后一个倒退到第一个。
那我该怎么办?
【问题讨论】:
至少有两种选择。
首先,要具体回答您关于在光标上向后迭代的问题,您可以执行以下操作:
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
// get stuff from the cursor
}
其次,您可以从 sql 以相反的顺序填充游标,然后以正常方式遍历游标:
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();
【讨论】:
您可以在最后一个位置开始光标,然后使用 moveToPrevious() 直到完成。
cursor.moveToLast();
do
{
// Stuff
}
while (cursor.moveToPrevious());
【讨论】: