Android数据库 – 由于连接池已关闭,无法执行此操作

我有一个奇怪的问题与 android数据库和光标.时间(很少)发生,我得到客户的崩溃报告.很难找出为什么它崩溃,因为我有大约15万活跃用户,也许每周一个报告,所以这真的是一些小错误.这是例外:
STACK_TRACE=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)
at android.database.sqlite.sqliteSession.executeForCursorWindow(sqliteSession.java:834)
at android.database.sqlite.sqliteQuery.fillWindow(sqliteQuery.java:62)
at android.database.sqlite.sqliteCursor.fillWindow(sqliteCursor.java:144)
at android.database.sqlite.sqliteCursor.getCount(sqliteCursor.java:133)
at sk.mildev84.agendareminder.a.c.a(SourceFile:169)

在每个游标“迭代和探索”之前,我使用这个代码确保一切正常:

db = instance.getWritableDatabase();
cursor = db.rawQuery(selectQuery,null);

if (isCursorEmptyOrNotPrepared(cursor)) {
    ...
    }

private synchronized boolean isCursorEmptyOrNotPrepared(Cursor cursor) {
        if (cursor == null)
            return true;

        if (cursor.isClosed())
            return true;

        if (cursor.getCount() == 0) // HERE IT CRASHES
            return true;

        return false;
    }

它落在下面

if (cursor.getCount() == 0)

有人知道为什么吗我想,我正在检查所有可能的例外和条件…为什么我的应用程序崩溃在这里

PS:所有的数据库方法是同步的,我正在打开和关闭数据库/游标在所有情况下,我检查了很多次.

解决方法

问题
如果在关闭数据库后尝试另一个操作,它会给你异常.因为db.close();释放对象的引用,如果最后一个引用被释放,则关闭该对象.

在静态上下文中保存一个sqliteOpenHelper实例(Singleton).做懒惰初始化,并同步该方法.如
public class DatabaseHelper
{
    private static DatabaseHelper instance;

    public static synchronized DatabaseHelper getInstance(Context context)
    {
        if (instance == null)
            instance = new DatabaseHelper(context);

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

你不必关闭它?当应用程序关闭时,它会放开文件引用,如果它甚至坚持下去.

即您不应该关闭数据库,因为它将在下次调用中再次使用.
所以只需删除

db.close();

欲了解更多信息,请参阅Single SQLite connection

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...