什么是迭代一个Android光标最好的方法是什么? [英] What's the best way to iterate an Android Cursor?

查看:135
本文介绍了什么是迭代一个Android光标最好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到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.

这篇关于什么是迭代一个Android光标最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆