Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would happen if I don't close the database in Android?

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.

  • My confusion is that is it necessary to close DB?
  • If so, what is the right place to do so, is it in onDestroy of the main activity or somewhere else?
  • If I don't close DB, what are the side effects?
like image 731
Ganesh K Avatar asked Jul 12 '12 07:07

Ganesh K


People also ask

Is DB Close necessary?

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.

What is the use of database in Android?

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.

When should SQLite database be closed?

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.

Where will Android databases be stored?

Just like files that you save on the device's internal storage, Android stores your database in your app's private folder.


1 Answers

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)

like image 82
Jin35 Avatar answered Oct 12 '22 23:10

Jin35