Do I need to close a Cursor if moveToFirst() is false?
Asked Answered
P

4

6

If cursor.moveToFirst() returns false do I still need to close it? Since it returns false when the cursor is empty.

I'm doubt about the correct approach:

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

Or:

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

    cursor.close();
}
Paderna answered 12/6, 2015 at 11:38 Comment(0)
C
2

You must close all Cursors which are not nulls, regardless of whether they have populated entries or not.

The only exception to the above statement would be if you know that the Cursor in question is managed by some "external" framework and will be automatically closed without your interaction (as is the case with LoaderManager framework when used with CursorLoader).

At least two (good) reasons to close any non-null Cursor:

  1. Empty Cursors can have "memory-allocations" which need to be explicitly released even if they are empty (as is the case with AbstractWindowedCursor)
  2. Empty Cursor can become non-empty if requery() is called. Your means to prevent this explicitly is to close the Cursor

The most general and error prone approach would be (it is an overkill in some cases):

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 Cursor's entries:

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

Don't feel bad with one extra c != null comparison - it is totally justified in these cases.

Confessional answered 12/6, 2015 at 12:5 Comment(0)
S
0

Closing an "empty" cursor doesn't hurt your app, call it anyway.

Theoretically, won't be any side effeects if you don't close it, but close it anyway, IMHO.

Swellhead answered 12/6, 2015 at 11:39 Comment(0)
B
0

From the official docs for Cursor.moveToFirst():

Move the cursor to the first row.

This method will return false if the cursor is empty.

It said that it will return false if the Cursor is empty, not null. How could Android know whether or not a cursor's empty? Exactly, it will open said cursor.

So yes, You'd still need to close it.

Bayer answered 12/6, 2015 at 11:53 Comment(0)
P
0
if (myCursor.moveToFirst()) {
    do {

          // work .....

    } while (myCursor.moveToNext());
}

or simply...

while (cursor.moveToNext()) {
    // use cursor
}
Pupa answered 12/6, 2015 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.