Exception: attempt to acquire a reference on a close SQLiteClosable
This one drove me insane for the longest time. The solution I have found is fairly simple: don't keep references to SQLiteDatabase
objects. Instead, use a SQLiteOpenHelper
and call getWritableDatabase()
every time you need one. From the docs:
public synchronized SQLiteDatabase getWritableDatabase()
Create and/or open a database that will be used for reading and writing. Once opened successfully, the database is cached, so you can call this method every time you need to write to the database.
The answer was right there the whole time.
SQLiteDatabase is closed automatically under some conditions.
http://darutk-oboegaki.blogspot.com/2011/03/sqlitedatabase-is-closed-automatically.html
getCount() and onMove() methods of Cursor trigger an actual query using SQLiteQuery. After all required data are obtained, SQLiteQuery decrements the reference count of the SQLiteDatabase instance. When the reference count reaches 0, the database is closed.
Note that the query may be executed asynchronously and in such a case, getCount() may return -1 if it is called before SQLiteQuery finishes preparing data.
I had same problem for a few days, and my solution was to put open() method just before my query and close() method after database operation. It looks something like this.
open();
Cursor cur=db.query(DATABASE_TABLE_CON, null, null, null, null, null, " name ASC");
close();
return cur;
It works just fine, but I'm concerned for resources cost. I'm not sure am I spending more resources with all this opening and closing database before any action.
I've been experiencing a similar problem, despite already following Jarett's advice. In my case the problem is happening fairly regularly on orientation changes. I've discovered that, for some reason I haven't yet got to the bottom of, my code generates two identical, pretty much simultaneous AsyncTasks on an orientation change (as opposed to just one when the activity starts normally). These tasks perform the same database query at the same time from different threads.
This exception (or occasionally some other SQLiteException) is the result. So it seems that this message can be a symptom of concurrency problems, even if it is not necessarily the root of the original problem posted here.