我对 android 数据库和游标有奇怪的问题。有时(很少)发生,我收到客户的崩溃报告。很难找出它崩溃的原因,因为我有大约 150 000 个活跃用户,可能每周大约有 1 个报告,所以这确实是一些小错误。这是例外:
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:所有数据库方法都是同步的,我在所有情况下都正确打开和关闭数据库/游标,我检查了很多次。
Problem
如果您在关闭数据库后尝试另一个操作,它会给您该异常。因为db.close();
释放对该对象的引用,如果释放了最后一个引用,则关闭该对象。
Solution
留个单SQLiteOpenHelper
实例(Singleton
)在静态上下文中。进行延迟初始化,并且synchronize
那个方法。例如
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...
}
And 你不必关闭它吗?当应用程序关闭时,它会释放文件引用(如果它还保留着它的话).
即您不应该关闭数据库,因为它将在下一次调用中再次使用。
所以只需删除
db.close();
欲了解更多信息,请参阅单个 SQLite 连接 http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)