qkx*_*qkx 14 database android android-cursor
我有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)
Run Code Online (Sandbox Code Playgroud)
在每个游标"迭代和探索"之前,我使用此代码确保一切正常:
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;
}
Run Code Online (Sandbox Code Playgroud)
它符合一致:
if (cursor.getCount() == 0)
Run Code Online (Sandbox Code Playgroud)
谁知道为什么?我想,我正在检查所有可能的例外情况和条件......为什么我的应用程序崩溃了?
PS:所有数据库方法都是同步的,我在所有情况下都正确地打开和关闭数据库/游标,我多次检查它.
Gir*_*hai 28
问题
如果在关闭数据库后尝试其他操作,它将为您提供该异常.因为db.close();释放对该对象的引用,如果最后一个引用被释放则关闭该对象.
解决方案
将单个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...
}
Run Code Online (Sandbox Code Playgroud)
而你不必关闭它?当应用程序关闭时,它会释放文件引用,如果它甚至坚持它.
即您不应关闭数据库,因为它将在下一次调用中再次使用.所以只需删除
db.close();
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅Single SQLite连接
| 归档时间: |
|
| 查看次数: |
20145 次 |
| 最近记录: |