【问题标题】:Do I need to close a Cursor if moveToFirst() is false?如果 moveToFirst() 为假,我是否需要关闭游标?
【发布时间】:2022-01-05 21:46:53
【问题描述】:

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

我怀疑正确的方法:

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

或者:

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

    cursor.close();
}

【问题讨论】:

    标签: android android-cursor


    【解决方案1】:

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

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

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

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

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

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

    如果您需要遍历 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();
    

    不要因为多了一个 c != null 比较而感到难过 - 在这些情况下这是完全合理的。

    【讨论】:

      【解决方案2】:

      关闭“空”光标不会伤害您的应用,无论如何都要调用它。

      理论上,如果你不关闭它不会有任何副作用,但无论如何都要关闭它,恕我直言。

      【讨论】:

        【解决方案3】:

        来自Cursor.moveToFirst()的官方文档:

        Move the cursor to the first row.
        
        This method will return false if the cursor is empty.
        

        它表示如果Cursorempty,它将返回false,而不是null。 Android如何知道光标是否为空?没错,它会打开所说的光标。

        所以是的,你仍然需要关闭它。

        【讨论】:

          【解决方案4】:
          if (myCursor.moveToFirst()) {
              do {
          
                    // work .....
          
              } while (myCursor.moveToNext());
          }
          

          或者干脆……

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

          【讨论】:

            猜你喜欢
            • 2014-02-26
            • 2012-09-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-15
            • 1970-01-01
            相关资源
            最近更新 更多