开发者

Android: do I really need to worry about closing SQLite database instances?

My Android application is frequently logging errors complaining that I failed to release my statements, cursors, and databases. In fact, I am explicitly releasing all of my cursors in finally{} blocks at the end of the code that uses them, and I'm closing m开发者_StackOverflow中文版y databases in the finalize() methods of the classes that contain them.

The structure of my application makes it very difficult for me to explicitly call the close() method on the database object (other than in the finalizer) because, for example, the class that uses the database is not an Activity class but may be a class that is used indirectly by an Activity. So that class does not itself know when the Activity to which it is ultimately attached is being destroyed.

Do I need to be concerned about this? Am I permentently leaking some resource by not explicitly closing my database instances? Is there any danger that something will fail to get written to the file? Does the SQLite implementation on Android do write caching? Can I turn it off or force a synchronization?

What is the Android VM's policy regarding finalizers - are they guaranteed to run eventually?

Frank


I found a force close issue in my app that was the result of an unclosed connection. In my case the the query was taking a long time and the user could go back to an activity and re-click forcing a new query.

I found this only while debugging the app as it ended up in a bit of the code that I didn't think possible at that point of execution.

Simply closing my connection resolved this. So, long story long it can't hurt to be tidy. Guessing you knew that anyway and you're just looking for validation?


Using SQLiteOpenHelper instead of SQLiteDatabase, may reduce some of the exceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜