I have an android application using an SQLite database. I open the database when the application starts, but never close it as it is in constant use.
What is the best way to tell the database to flush all its changes to permanent storage? Do I need to just close it and re-open or is there a more efficient way?
My problem is that when testing on a phone, turning the phone off after a number of writes sometimes causes the database to loose the most recent updates when the application is restarted, which is obviously unacceptable for a database system.
Since I cannot find out how to capture the application close event I cannot know when to manually close the database.
Don’t do that. You are apparently ignoring all the errors that are appearing in LogCat complaining that you are leaking database connections.
It will do that automatically at the end of a transaction. By default, each individual SQL operation (e.g., insert) is a transaction.
You should close your database at some point (e.g.,
onDestroy()of the service that is mediating your database).If you can create a sample project that demonstrates the problem even after you are properly closing your database connection, post it to the Android issue tracker.
Close it when all activities have unbound from the service that is mediating the database connection, triggering that service’s
onDestroy()method.Or, open a fresh connection in each component that needs access to the database, and use Java synchronization to ensure two threads do not try to simultaneously use the database (if needed).