SQLite IllegalStateException:在哪里关闭数据库?
在 Android 中创建和填充新的 SQLiteDatabase 时,我遇到两个相互矛盾的异常。简而言之,我的代码:
SQLiteOpenHelper 扩展类:
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_TABLE_CREATE);
loadLevelData(db); //puts data in the database
//db.close(); <<< ?
}
在我的活动类中,我实例化该类(在 onCreate() 中),并调用 getWritableDatabase():
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
现在,如果我不调用 db.close () 填充数据库后,像上面一样,我得到
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
但是如果我关闭它,我会得到以下异常:
java.lang.IllegalStateException: database not open
在 getWritableDatabase() 上。
这真的让我很困惑,所以有人可以帮助我解决问题吗?
I'm getting two contradicting Exceptions when creating and populating my new SQLiteDatabase in Android. In short my code:
SQLiteOpenHelper extending class:
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_TABLE_CREATE);
loadLevelData(db); //puts data in the database
//db.close(); <<< ?
}
In my activity class I instantiate this class (in onCreate()), and call getWritableDatabase():
dbHelper = new DbOpenHelper(getApplicationContext());
database = dbHelper.getWritableDatabase();
Now if I don't call db.close()
after populating the database, like above, I get
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
However if I DO close it, I get the following exception:
java.lang.IllegalStateException: database not open
on getWritableDatabase().
This really confuses me, so could anyone help me with what's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要在
DatabaseHelper
类中关闭数据库。但是,每次调用 getWritableDatabase 打开它时都需要将其关闭:You are not expected to close the database in the
DatabaseHelper
class. However you need to close it every time you open it callinggetWritableDatabase
:您在错误的时间关闭数据库。
我通常像这样保留数据库:
或者,将使用该数据库连接的所有代码包装在 try/finally 块中
注意:所有打开/关闭都应该在使用该数据库连接的活动中完成数据库,而不是开放助手。
You are closing your database at the wrong time.
I typically keep the database around like this:
Alternatively, wrap all your code working with that db connection in a try/finally block
Note: All of the opening/closing should be done in the Activity working with the database, not the open helper.