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();
}
source to share
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 withAbstractWindowedCursor
) - Empty
Cursor
can become non-empty if calledrequery()
. 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.
source to share
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.
source to share