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

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

问题描述

我经常看到代码,它涉及迭代数据库查询的结果,对每一行做一些事情,然后移动到下一行。典型的例子如下。

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



这些都看起来太长了, code> Cursor 方法。

推荐答案

最简单的方法是:

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.

当然,不要忘记关闭光标,重做它,最好在 finally 子句。

Of course, don't forget to close the cursor once you're done with it, preferably in a finally clause.

Cursor cursor = db.rawQuery(...);
try {
    while (cursor.moveToNext()) {
        ...
    }
} finally {
    cursor.close();
}

如果您的目标是API 19+,您可以使用try-with-resources。

If you target API 19+, you can use try-with-resources.

try (Cursor cursor = db.rawQuery(...)) {
    while (cursor.moveToNext()) {
        ...
    }
}

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

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