Android:无法执行此操作,因为连接池已关闭 [英] Android: Cannot perform this operation because the connection pool has been closed

查看:47
本文介绍了Android:无法执行此操作,因为连接池已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 StackOverflow 关于这个问题,但我仍然没有找到解决方案.我注意到有时,我的应用程序会抛出此错误:

I was reading through StackOverflow about this question and I still haven't found a solution. I notice that sometimes, my app throws this error:

   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 的文件,使用这种方法来获取它的实例:

I have a file called DatabaseHelper.java using this approach to get an instance of it:

public static DatabaseHelper getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return mInstance;
}

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

Then I have methods like this one (that it crashed in the line cursor.moveToFirst() with that error). It almost never crashes, but sometimes it does.

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;
}

就是这样,在我使用的所有方法中:

So that's it, in all the methods I use:

SQLiteDatabase db = this.getReadableDatabase(); (or Writable)

然后我关闭游标和数据库.在这种情况下,错误被抛出:

And then I close the cursor and the db. In this case, the error got throw in the line:

cursor.moveToFirst();

如果我之前调用 this.getReadableDatabase(),我不明白为什么错误说数据库已关闭.请支持!谢谢:)

I do not see why the error says the db is closed if I am calling this.getReadableDatabase() before. Please support! Thank you :)

推荐答案

移除

db.close();

如果你在关闭数据库后尝试另一个操作,它会给你那个异常.

If you try another operation after closing the database, it will give you that exception.

文档 说:

释放对对象的引用,关闭对象...

另外,看看Android SQLite 关闭异常关于 Android 框架工程师的评论,该评论指出没有必要关闭数据库连接,但是这只是在 ContentProvider 中管理时才需要.

Also, check out Android SQLite closed exception about a comment from an Android Framework engineer which states that it is not necessary to close the database connection, however this is only when it is managed in a ContentProvider.

这篇关于Android:无法执行此操作,因为连接池已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆