When should I call close() on SQLiteOpenHelper used by ContentProvider

风流意气都作罢 提交于 2019-12-17 18:37:35

问题


In my android app, I use SQLiteOpenHelper to implements ContentProvider. Query, add, delete operations are all through ContentProvider.

But in one of my android phone(htc g13), I found *.db-wal file in directory /data/data/[package name]/databases. And the file size increate very fast when operating with ContentProvider. It occupied user RAM space too much.

It is recommended to close the SQLiteOpenHelper to solve my problem (it is useful) in post enter link description here.

But I want to find a "place" to add the "close()" method since I am not using SQLiteOpenHelper directly (using through ContentProvider). query() method in ContentProvider must return a Cursor, and SQLiteDatabse should stay in open state.

I'm confused, what show I do now to keep *.db-wal gone and use ContentProvider normally?


回答1:


Android framework engineer defer to this view that you need to close the DB.

As per Dianne Hackborn(Android Framework Engineer) in this thread:

A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database -- it will get closed as part of the kernel cleaning up the process's resources when the process is killed.




回答2:


You have a couple of cases to cover:

1) When your application finishes (e.g. entering onDestroy()) make sure you close all Cursors, Database instances of SQLiteDatabase and SQLiteOpenHelpers (using the model if (connection.isOpen()) object.close())

2) When you application goes onPause() -> onResume() - use this stages appropriately to pause/resume your connection or to close/open them.

It's a good practice to close your database immediately after you finish working with it. The database is cached, so there's no problem closing it and re-acquire instance again when you need it with getWritableDatabase()/getReadableDatabase()

From the official doc: "Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close() when you no longer need the database.)"

Also keep in mind that if SQLiteOpenHelper caches and tracks all open instances of SQLiteDatabase, it basically means that if you don't leave open database connections, you won't have to call close on SQLiteOpenHelper.

I recommend closing all cursors and databases immediately after you stop working with them. Always try to enforce try/catch/ for queries operations and a "finally block" to call the close methods on the objects.



来源:https://stackoverflow.com/questions/8531201/when-should-i-call-close-on-sqliteopenhelper-used-by-contentprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!