如何解决:java.lang.IllegalStateException:由于连接池已关闭,无法执行此操作?

问题描述 投票:0回答:2

我有android数据库和游标的问题。不时(非常罕见)发生,我收到客户的崩溃报告。很难找出它崩溃的原因,所以它确实是一个小错误。

这是例外:

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)

然后我有像这样的方法(它在c.moveToNext()行中崩溃并出现该错误)。它几乎从不崩溃,但有时它会,我无法重现它。

public List<AlarmModel> getAlarms() {
    SQLiteDatabase db = this.getReadableDatabase();

    String select = "SELECT * FROM " + Alarm.TABLE_NAME +" WHERE "+ Alarm.COLUMN_NAME_ALARM_FLAVOR_ID+" = -1 ";

    Cursor c = db.rawQuery(select, null);

    List<AlarmModel> alarmList = new ArrayList<AlarmModel>();

    while (c.moveToNext()) {
        alarmList.add(populateModel(c));
    }

    if (!alarmList.isEmpty()) {
        if (db != null) {
            db.close();
        }
        if (c != null) {
            c.close();
        }
        return alarmList;
    }

    return null;
}
android
2个回答
0
投票

多个事情可能会导致此问题:您在访问数据之前调用db.close()。湾或者其他方法正在调用db.close(),并且您仍在尝试从具有相同数据库引用的其他方法访问数据库中的数据。


0
投票

删除db.close()

这可能是一个多线程问题,db由另一个线程关闭。您可以检查db.close()的所有位置。

我通常在Application.onStart()中打开数据库,只在Application.onDestroy()中关闭它。因此无需担心多线程数据库的打开/关闭。

© www.soinside.com 2019 - 2024. All rights reserved.