Why is my cursor not closed in Android activity?

In my Android operation, I need to read things from the database. I created a helper class that relates to my access to the database. This helper class has several different methods designed to read different things and return them without any problems. Here is one example.

public String GetName(int id) { String toReturn = null; Cursor cursor = null; try { cursor = db.query(TABLE_NAME, new String[] {"name"}, "id = " + id, null, null, null, null, null); assert(cursor.getCount() == 1); cursor.moveToFirst(); toReturn = new String(cursor.getString(0)); } finally { if(cursor != null) cursor.close(); } return toReturn; } 

I keep getting an error

10-10 15: 52: 18.991: W / SQLiteCompiledSql (28313): release the statement in the finalizer. Make sure you explicitly call close () in your cursor: SELECT name FROM my_table WHERE id = 0 10-10 15: 52: 18.991: W / SQLiteCompiledSql (28313): android.database.sqlite.DatabaseObjectNotClosedException: the application did not close the cursor object or database that was opened here

with a stack trace that leads directly to this function (and is very similar to it), although Activity works fine. What am I doing wrong? I looked around a bit and when I added try / finally to make sure I always close the cursor, but I still get the error. How can i fix this?

+4
source share
1 answer

You close the cursor correctly, but you also need to close the database, make sure that you also close the database:

 if(db.isOpen()) db.close(); 
+2
source

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


All Articles