我有一个数据库助手对象。离开活动时关闭它很重要,所以我这样做。但是,在返回活动时,我收到有关查询已关闭的数据库的警告。查询确实有效,但仍然存在明显的错误。
我对Android活动生命周期的理解并不强烈,但我认为我需要在onResume()中重新打开数据库。这不正确吗?
这是onResume():
@Override
protected void onResume() {
super.onResume();
dbHelper.setInteger(playerID);
dbHelper.openDataBase();
ourCursor = dbHelper.getPlayerSavedQuestions();
startManagingCursor(ourCursor);
adapter = new MyCustomAdapter(ourCursor);
myListView.setAdapter(adapter);
}
这是dbHelper.openDataBase();
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
这是我的logcat:
06-15 13:51:32.388: W/SQLiteCursor(26750): requery() failed database /data/data/com.boboshi.exquizit.eng/databases/exquizit_custom.mp3 (conn# 0) already closed
06-15 13:51:32.388: W/SQLiteCursor(26750): java.lang.IllegalStateException: database /data/data/com.boboshi.exquizit.eng/databases/exquizit_custom.mp3 (conn# 0) already closed
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.database.sqlite.SQLiteDatabase.verifyDbIsOpen(SQLiteDatabase.java:2082)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.database.sqlite.SQLiteDatabase.getDbConnection(SQLiteDatabase.java:2407)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.database.sqlite.SQLiteDatabase.getDatabaseHandle(SQLiteDatabase.java:2388)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.database.sqlite.SQLiteCursor.requery(SQLiteCursor.java:246)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.Activity.performRestart(Activity.java:4505)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.Activity.performResume(Activity.java:4531)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1173)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.os.Looper.loop(Looper.java:137)
06-15 13:51:32.388: W/SQLiteCursor(26750): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-15 13:51:32.388: W/SQLiteCursor(26750): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 13:51:32.388: W/SQLiteCursor(26750): at java.lang.reflect.Method.invoke(Method.java:511)
06-15 13:51:32.388: W/SQLiteCursor(26750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-15 13:51:32.388: W/SQLiteCursor(26750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-15 13:51:32.388: W/SQLiteCursor(26750): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
您需要在onResume
中实例化您的dbhelper类...当您离开活动时也会(可能)被销毁。
dbHelper = new YourDatabaseHelper();
实际上,由于即使在新的开始时调用onResume
,您也可以将所有代码移动到那里(从而避免两次实例化助手(以及做其他事情)。