关闭数据库是否必不可少?

Ten*_*r04 13 sqlite android

在Google的记事本示例中,它们似乎不关闭数据库,至少不在onDestroy()中.

关闭它的目的是什么,我真的需要吗?开放数据库是否会占用大量内存?我发现在onDestroy中关闭它会留下漏洞,如果有任何运行的线程可能会在Activity完成后尝试访问它.

Far*_*ray 11

如果不关闭数据库连接,它们将导致内存泄漏.

记事本示例确实使用startManagingCursor,但您仍需要显式关闭数据库连接.按原样运行记事本示例并连续编辑几个注释,您将看到它开始在LogCat中抛出警告和错误.(在较大的应用程序中,您也将开始看到内存泄漏检测警告.)

W/SQLiteCompiledSql(  302): Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor: INSERT INTO notes(body, title) VALUES(?, ?);
W/SQLiteCompiledSql(  302): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
W/SQLiteCompiledSql(  302):     at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:62)
...
W/SQLiteCompiledSql(  302):     at dalvik.system.NativeStart.main(Native Method)
E/Database(  302): close() was never explicitly called on database '/data/data/com.android.demo.notepad3/databases/data' 
E/Database(  302): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
E/Database(  302):  at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1810)
...
E/Database(  302):  at dalvik.system.NativeStart.main(Native Method)
Run Code Online (Sandbox Code Playgroud)

您提到onDestroy()在任何仍在运行的非UI线程中"保留漏洞".如果您使用的是AsyncTask,则可以getStatus在任务中检查这些线程的状态.

if ( myAsyncTask.getStatus() == AsyncTask.Status.FINISHED ){
    mDbHelper.close();
}
Run Code Online (Sandbox Code Playgroud)

然后在onPostExecute你的方法中关闭连接AsyncTask.

希望有帮助......