Do I need to close the cursor if moveToFirst () is false?

If it cursor.moveToFirst()

returns false, do I still need to close it? Because it returns false when the cursor is empty.

I doubt the correct approach:

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

      

Or:

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

    cursor.close();
}

      

+3


source to share


4 answers


You have to close all Cursors

that are not zeros, whether they have filled records or not.

The only exception to the above statement would be if you know that the one in question is Cursor

driven by some "external" framework and will be automatically closed without your interaction (as is the case with framework LoaderManager

when used with CursorLoader

).

At least two (good) reasons for closing any non-zero Cursor

:

  • Empty Cursors

    may have "memory allocations" that must be explicitly released, even if empty (as is the case with AbstractWindowedCursor

    )
  • Empty Cursor

    can become non-empty if called requery()

    . Your means to prevent this is clearly to closeCursor

The most common approach and error prone (in some cases overkill):



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

      

Another popular pattern if you need to iterate over records Cursor's

:

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

      

Don't feel bad with one extra comparison c != null

- it's totally justified in these cases.

+1


source


Closing an "empty" cursor won't harm your application, call it anyway.



In theory, there won't be any side effects if you don't close it, but close it anyway, IMHO.
0


source


From the official docs for Cursor.moveToFirst()

:

Move the cursor to the first row.

This method will return false if the cursor is empty.

      

He said that it would return false if Cursor

empty, not null. How could Android know if the cursor is empty? Exactly, it will open the specified cursor.

So yes, you still need to close it.

0


source


if (myCursor.moveToFirst()) {
    do {

          // work .....

    } while (myCursor.moveToNext());
}

      

or simply...

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

      

0


source







All Articles