Skip to content
Advertisement

Android: Cannot perform this operation because the connection pool has been closed

I was reading through StackOverflow about this question and I still haven’t found a solution. I notice that sometimes, my app throws this error:

   java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
        at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:962)
        at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:599)
        at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
        at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
        ...

I have a file called DatabaseHelper.java using this approach to get an instance of it:

public static DatabaseHelper getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return mInstance;
}

Then I have methods like this one (that it crashed in the line cursor.moveToFirst() with that error). It almost never crashes, but sometimes it does.

public Profile getProfile(long id) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT * FROM " + TABLE_PROFILES + " WHERE " + KEY_PROFILES_ID + " = " + id;
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    Profile profile = new Profile();
    if (cursor.moveToFirst()) {
        doWhatEver();
    }
    cursor.close();
    db.close();

    return profile;
}

So that’s it, in all the methods I use:

SQLiteDatabase db = this.getReadableDatabase(); (or Writable)

And then I close the cursor and the db. In this case, the error got throw in the line:

cursor.moveToFirst();

I do not see why the error says the db is closed if I am calling this.getReadableDatabase() before. Please support! Thank you 🙂

Advertisement

Answer

Remove

db.close();

If you try another operation after closing the database, it will give you that exception.

The documentation says:

Releases a reference to the object, closing the object…

Also, check out Android SQLite closed exception about a comment from an Android Framework engineer which states that it is not necessary to close the database connection, however this is only when it is managed in a ContentProvider.

Advertisement