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?Because key/data pairs are cached in memory, applications should make a point to always either close database handles or sync their data to disk (using the DB->sync() method) before exiting, to ensure that any data cached in main memory are reflected in the underlying file system.
SQLite Database is an open-source database provided in Android which is used to store data inside the user's device in the form of a Text file. We can perform so many operations on this data such as adding new data, updating, reading, and deleting this data.
Really, you don't have to close database connection. You can save database as a field in Application object. Official documentation doesn't say anything about time of database closing. Also this question quotes an old (deleted now) post of Google engineer which says, that this approach is OK.
Just like files that you save on the device's internal storage, Android stores your database in your app's private folder.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With