Skip to content Skip to sidebar Skip to footer

Android Database - Cannot Perform This Operation Because The Connection Pool Has Been Closed

I have strange problem with android database and cursors. Time to time (very rarely) happens, that I got crash report from customers. It's hard to find out why it crashes, as I hav

Solution 1:

Problem If you try another operation after closing the database, it will give you that exception.Because db.close(); releases a reference to the object, closing the object if the last reference was released. Solution Keep a single SQLiteOpenHelper instance(Singleton) in a static context. Do lazy initialization, and synchronize that method. Such as

publicclassDatabaseHelper
{
    privatestatic DatabaseHelper instance;

    publicstaticsynchronized DatabaseHelper getInstance(Context context)
    {
        if (instance == null)
            instance = newDatabaseHelper(context);

        return instance;
    }
//Other stuff... 
}

And you don't have to close it? When the app shuts down, it’ll let go of the file reference, if its even holding on to it. i.e. You should not close the DB since it will be used again in the next call. So Just remove

db.close();

For more info See at Single SQLite connection

Solution 2:

The problem is clear that

SQLiteCursor cannot perform 'getCount' operation because the connection pool has been closed

To avoid IllegalStateException, we may keep the database open all the time if that is appropriate. In other situations we need to check the status before trying getCount.

My experience is as follows:

Defective Code:

SOLiteOpenHelperhelper=newSOLiteOpenHelper(context);
SQLiteDatabasedb= helper.getWritableDatabase();
Cursorcursor= db.query(...);
if (cursor != null) {
    cursor.getCount(); // HERE IT CRASHES
}

Perfect Code:

SOLiteOpenHelperhelper=newSOLiteOpenHelper(context);
SQLiteDatabasedb= helper.getWritableDatabase();
Cursorcursor= db.query(...);
if (cursor != null && db.isOpen()) {
    cursor.getCount(); // OK!
}

Solution 3:

I had this problem too. my SQLiteOpenHelper class was Singleton as well as closing the db after each CRUD operation. After I make my methods(CRUD) synchronized in my SQLiteOpenHelper class, I didn't get error any more :)

Solution 4:

Same problem occured to me, so after reading explanation I removed db.close(); from public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) andpublic int delete(Uri uri, String selection, String[] selectionArgs) method of ContentProvider No need of db.close() as ContentProvider itself take care of closing of database.

Post a Comment for "Android Database - Cannot Perform This Operation Because The Connection Pool Has Been Closed"