我经常看到这样的代码:遍历数据库查询的结果,对每一行执行一些操作,然后移动到下一行。典型例子如下。

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());
}

在我看来,这些方法都过于冗长,每个方法都有多个Cursor方法调用。肯定有更整洁的方法吧?


当前回答

if (cursor.getCount() == 0)
  return;

cursor.moveToFirst();

while (!cursor.isAfterLast())
{
  // do something
  cursor.moveToNext();
}

cursor.close();

其他回答

Do/While解决方案更优雅,但如果你只使用上面发布的While解决方案,没有movetopposition(-1),你将错过第一个元素(至少在Contact查询中)。

我建议:

if (cursor.getCount() > 0) {
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
          <do stuff>
    }
}

下面可能是更好的方法:

if (cursor.moveToFirst()) {
   while (!cursor.isAfterLast()) {
         //your code to implement
         cursor.moveToNext();
    }
}
cursor.close();

上面的代码将确保它将通过整个迭代,而不会在第一次和最后一次迭代中逃脱。

我只想指出第三种选择,如果光标不在起始位置,它也可以工作:

if (cursor.moveToFirst()) {
    do {
        // do what you need with the cursor here
    } while (cursor.moveToNext());
}

游标是Interface,表示任何数据库的二维表。

当您尝试使用SELECT语句检索一些数据时,数据库将首先创建一个CURSOR对象并将其引用返回给您。

这个返回引用的指针指向第0个位置,也就是光标的第一个位置,所以当你想从光标中检索数据时,你必须首先移动到第1条记录,所以我们必须使用moveToFirst

当您在游标上调用moveToFirst()方法时,它将游标指针指向第一个位置。现在可以访问第一条记录中的数据了

最佳观赏方式:

鼠标光标

for (cursor.moveToFirst(); 
     !cursor.isAfterLast();  
     cursor.moveToNext()) {
                  .........
     }

我所发现的浏览光标的最佳方式如下:

Cursor cursor;
... //fill the cursor here

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
    // do what you need with the cursor here
}

之后不要忘记关闭光标

编辑:如果你需要迭代一个你不负责的游标,给出的解决方案是很好的。一个很好的例子是,如果你在一个方法中使用一个游标作为参数,你需要扫描游标以获得一个给定的值,而不必担心游标的当前位置。