This title may sound a little bit crazy, but this is what is making me confused. My app heavily uses local database operations. As suggested in the Android docs and some blogs, I extended the SQLiteOpenHelper
class and defined all my DB operations there. As some of my DB operations execute in threads, opening and closing of the db causes some IllegalStateExceptions
. So, I made my DB helper as Singleton
and it resolved those issues, also getting rid of the open
and close
operations for every DB action. Now everything seems to be working fine even though I never close the DB.
onDestroy
of the main activity or somewhere else? You can catch IllegalStateException
if you'll try to open again the same database.
If you create instance of DBHelper
in onCreate
method of main activity - it would be write to close db in onDestroy
. So, you can be sure, that next time in onCreate
your database is not opened already.
If you have reference to DBHelper
in service, than it should be opened and closed in service, and not in activity.
You can also use Application
class for opening db, but than it will opened every time when you app starts (for example when you receive BroadcastReceiver
)
The reason why you get exceptions is that you are trying to write/read from the same database via different threads .
I believe the best place to close your database would be inside the onDestroy()
of your mainActivity .
我遇到了同样的问题。我打开数据库,执行一些操作,我忘了关闭。实际上我看到了一些例外我的logcat是“泄漏发现”db打开并且从未关闭。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.