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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With