我正在通过 StackOverflow 阅读有关此问题的信息,但仍未找到解决方案。我注意到有时我的应用程序会抛出此错误:
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)
...
我有一个名为 DatabaseHelper.java
的文件,使用这种方法获取它的一个实例:
public static DatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHelper(context.getApplicationContext());
}
return mInstance;
}
然后我有这样的方法(它在 cursor.moveToFirst()
行崩溃并出现该错误)。它几乎从不崩溃,但有时会崩溃。
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;
}
就是这样,在我使用的所有方法中:
SQLiteDatabase db = this.getReadableDatabase(); (or Writable)
然后我关闭游标和数据库。在这种情况下,错误在行中抛出:
cursor.moveToFirst();
如果我之前调用 this.getReadableDatabase()
,我不明白为什么错误说数据库已关闭。请支持!谢谢 :)
原文由 Ferran Negre 发布,翻译遵循 CC BY-SA 4.0 许可协议
消除
如果你在关闭数据库后尝试另一个操作,它会给你那个异常。
文件 说:
另外,查看 Android SQLite 关闭的异常,关于来自 Android Framework 工程师的评论,该评论指出没有必要关闭数据库连接,但这仅当它在
ContentProvider
中管理时。