9

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?
JJD
  • 50,076
  • 60
  • 203
  • 339
Ganesh K
  • 2,623
  • 9
  • 51
  • 78

3 Answers3

2

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)

Jin35
  • 8,602
  • 3
  • 32
  • 52
0

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.

Swayam
  • 16,294
  • 14
  • 64
  • 102
0

I faced same problem.I opened database ,perform some operation and i forget to close.Actually i saw some exceptions i logcat that is "Leak found" db is opened and never closed.

prakash .k
  • 635
  • 2
  • 12
  • 24