如果moveToFirst()为false,是否需要关闭Cursor?

Luc*_*ima 5 android cursor

如果cursor.moveToFirst()返回false,我还需要关闭吗?因为当光标为空时它返回false.

我怀疑正确的方法:

if (cursor != null && cursor.moveToFirst()) {
    // some code
    cursor.close();
}
Run Code Online (Sandbox Code Playgroud)

要么:

if(cursor != null) {
    if (cursor.moveToFirst()) {
        // some code
    }

    cursor.close();
}
Run Code Online (Sandbox Code Playgroud)

Vas*_*liy 2

您必须关闭所有Cursors非空值,无论它们是否已填充条目。

上述声明的唯一例外是,如果您知道相关问题Cursor是由某个“外部”框架管理的,并且将在没有您交互的情况下自动关闭(与LoaderManager一起使用时框架的情况就是如此CursorLoader)。

至少有两个(好的)理由来关闭任何非 null Cursor

  1. Cursors可以有“内存分配”,即使它们是空的也需要显式释放(与 的情况一样AbstractWindowedCursor
  2. 如果被调用,EmptyCursor可以变成非空。requery()明确防止这种情况的方法是关闭Cursor

最通用且容易出错的方法是(在某些情况下这是一种矫枉过正的做法):

Cursor c;
try {
    // Assign a cursor to "c" and use it as you wish
} finally {
    if (c != null) c.close();
}
Run Code Online (Sandbox Code Playgroud)

如果您需要迭代Cursor's条目,另一种流行的模式是:

if (c != null && c.moveToFirst()) {
    do {
        // Do s.t. with the data at current cursor's position
    } while (c.moveToNext());
}
if (c != null) c.close();
Run Code Online (Sandbox Code Playgroud)

不要因为额外的c != null比较而感到难过——在这些情况下这是完全合理的。