Closing a cursor in an SQLite database is explicitly necessary or not necessary?

I understand that after closing the database, the cursor becomes "invalid", does it also close the cursor at the same time? Does this not allow you 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(); } 
+4
source share
1 answer

The cursor is not closed in the strict sense, closing the database (it still exists, and you can perform operations on it), but as you know, closing the database makes the cursor useless. You must close the cursors explicitly after you finish using them for several reasons:

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

2) You will see warnings in LogCat;

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

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

+5
source

Source: https://habr.com/ru/post/1481683/


All Articles