发现Android数据库泄漏

时间:2012-04-04 08:53:38

标签: android database getwritabledatabase

当我输入另一个活动以将新项目插入数据库时​​,返回然后进入该活动它会给我一个错误:

04-03 18:53:26.914: E/Database(18134): Leak found
04-03 18:53:26.914: E/Database(18134): java.lang.IllegalStateException: /data/data/com.app.myapp/databases/BabyApp.db SQLiteDatabase created and never closed
04-03 18:53:26.914: E/Database(18134):  at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1695)
04-03 18:53:26.914: E/Database(18134):  at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:739)
04-03 18:53:26.914: E/Database(18134):  at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:761)
04-03 18:53:26.914: E/Database(18134):  at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:754)
04-03 18:53:26.914: E/Database(18134):  at android.app.ApplicationContext.openOrCreateDatabase(ApplicationContext.java:473)
04-03 18:53:26.914: E/Database(18134):  at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:193)
04-03 18:53:26.914: E/Database(18134):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
04-03 18:53:26.914: E/Database(18134):  at com.app.myapp.DatabaseHelper.open(DatabaseHelper.java:121)
04-03 18:53:26.914: E/Database(18134):  at com.app.myapp.SettingsActivity.init(SettingsActivity.java:80)

这是DatabaseHelper.java:121

database = dbHelper.getWritableDatabase();

这里是SettingsActivity 80行代码:

if (!db.isOpen())
            db.open();

2 个答案:

答案 0 :(得分:2)

确保执行db.close();以便在切换到其他活动之前关闭数据库

@Override
protected void onStop() {
    super.onStop();

    //closing database connection
    if(db != null)
        db.close();
}

答案 1 :(得分:0)

你也应该关闭它...当发生异常时关闭它,或者在任何情况下它都应该永远不会被打开,因为它的系统资源