I discovered in my project that the close() function in the SQLiteDatabase implementation on Android throws a NullPointerException when running multiple threads that open th
You don't need to bother. See this discussion which includes confirmation that closing the database is done by the system as needed if/when the process is killed off.
The relevant quote, from a Google employee, is:
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.
Looks similar to this issue: SQLiteDatabase close() function causing NullPointerException when multiple threads
You may not need to call database.close()
If you are working directly on a SQLite database without resorting to a content provider, a pattern I have seen used is to close the database in Application.onTerminate
, whereas the Application
instance stores the singleton database "adapter", which would be an object containing a SQLiteDatabase
and its SQLiteOpenHelper
.
I have your answers!
Never close the db. It is that simple.
Make sure you only have one, repeat, *one Helper instance per application. Share it with all threads.
http://www.touchlab.co/blog/single-sqlite-connection/
Here's some more info on the internals of sqlite and locking:
http://www.touchlab.co/blog/android-sqlite-locking/