Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

closing Cursor in SQLite database explicitly, needed or not needed?

I understand that a after a database is closed, the cursor becomes "invalid", does that also close the cursor at the same time? Does that avoid having to do what is shown below?

example 1

 public void String getResultsAndReturnString() {
      String result = "";
      SQLiteDatabase db = dbHelper.getReadableDatabase();
      Cursor cursor = qb.query(db, projection, null, null,
                    null, null, null);
      cursor.close();  <-- explicit cursor close example one
      db.close();
     return result;
  }

example 2

public void Cursor getResultsAndReturnCursor(){
   SQLiteDatabase db = dbHelper.getReadableDatabase();
   Cursor cursor = qb.query(db, projection, null, null,
                    null, null, null);
   return cursor;
}

public void closeOut(Cursor cursor, SQLiteDatabase dataBase){
     cursor.close();   <-- explicit cursor close example two
     dataBase.close();
}
like image 956
Kevik Avatar asked May 20 '13 02:05

Kevik


1 Answers

The cursor isn't closed in the strict sense by closing the database (it's still there and you can perform operations on it), but as you know, closing the database makes the cursor useless. You should close cursors explicitly after you're done using them for a number of reasons:

1) As you noted, after closing the database, any remaining cursors become "invalid," and cannot be relied upon for accurate data;

2) You will see warnings in LogCat;

3) You risk memory leaks if you maintain a reference to a cursor; and

4) It's simply good programming practice to close out resources that you no longer need.

like image 74
MarsAtomic Avatar answered Nov 09 '22 15:11

MarsAtomic