Closing the database safely
My application has some Activities and a Service that both read and write from the same SQLite database. To keep them synched up, I use a singleton instance of a SQLiteDatabase object.
However, every once in a while, I get a stack trace through the Android Market console from a customer, and it shows that something tried to access an already closed database.
Currently, my Activities always open and close the database in onCreate and in onPause (if isFinishing). When an Activity has the database open, it also switches a static boolean to keep my Service from closing it. My Service (which runs periodically based on an AlarmManager) always opens and immediately closes it once it reads what it needs to. But the service wil开发者_JAVA百科l not close the database if that static boolean from the Activity is on.
I'm not sure where my hole could be, and whether I really need to be closing the database all the time if I have a service periodically using it anyway.
You should close your database in the onDestroy
method to avoid that problem.
It's true that sometimes onDestroy
does not get called, but it does not really matter. If the OS takes down your process all the resources are going to be cleaned up anyway.
精彩评论