I have an android application using an SQLite database. I open the database when the applicati开发者_运维问答on 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.
I open the database when the application starts, but never close it as it is in constant use.
Don't do that. You are apparently ignoring all the errors that are appearing in LogCat complaining that you are leaking database connections.
What is the best way to tell the database to flush all its changes to permanent storage?
It will do that automatically at the end of a transaction. By default, each individual SQL operation (e.g., insert) is a transaction.
Do I need to just close it and re-open or is there a more efficient way?
You should close your database at some point (e.g., onDestroy()
of the service that is mediating your database).
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.
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.
Since I cannot find out how to capture the application close event I cannot know when to manually close the database.
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).
If you use any transactions they are nested. Meaning if you break out of one before ending it. You'll end up with some writes rolled back when the phone/app is restarted since you never close the connection.
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Is that on a Droid? And how exactly do you turn the phone off? Unless you pull the battery out, shutting down the phone will slowly wind down the operating system, at which point it will commit everything to memory.
When exactly do you lose your database? After every app restart, or just randomly? If it's after every restart, it sounds more like you're destroying the database on startup.
精彩评论