什么是迭代一个Android光标最好的方法是什么?最好的、光标、迭代、方法

2023-09-11 20:14:51 作者:super model

我经常看到code涉及循环访问一个数据库查询的结果,做一些与每一行,然后移动到下一行。典型的例子如下。

I frequently see code which involves iterating over the result of a database query, doing something with each row, and then moving on to the next row. Typical examples are as follows.

Cursor cursor = db.rawQuery(...);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) 
{
    ...
    cursor.moveToNext();
}

Cursor cursor = db.rawQuery(...);
for (boolean hasItem = cursor.moveToFirst(); 
     hasItem; 
     hasItem = cursor.moveToNext()) {
    ...
}

Cursor cursor = db.rawQuery(...);
if (cursor.moveToFirst()) {
    do {
        ...                 
    } while (cursor.moveToNext());
}

这些都显得过于啰嗦对我来说,每多次调用光标的方法。当然,必须有一个更合适的方法?

These all seem excessively long-winded to me, each with multiple calls to Cursor methods. Surely there must be a neater way?

推荐答案

最简单的方法是这样的:

The simplest way is this:

while (cursor.moveToNext()) {
    ...
}

光标开始的 的第一个结果行之前,因此第一次迭代这将移动到第一个结果的(如果存在)。如果光标是空的,或最后一行已经被处理后,则环路退出整齐

The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.