Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 281
Lucas Lima Avatar asked Jun 12 '15 11:06

Lucas Lima


People also ask

What is Cursor moveToFirst?

Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. . moveToFirst() method move it to the first row of result table.

What is the use of Cursor in Android?

Introduction to Cursor in Android The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory. Here, we pass the table name, column name only then we receive the cursor.

What is Cursor moveToNext?

moveToNext move the cursor to the next row. and c.getString(0) will always give you the first column if there is one.

What is Cursor class how it is used?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.


1 Answers

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.

like image 169
Vasiliy Avatar answered Oct 26 '22 18:10

Vasiliy