Android:我真的需要担心关闭 SQLite 数据库实例吗?
我的 Android 应用程序经常记录错误,抱怨我未能释放我的语句、游标和数据库。事实上,我在使用它们的代码末尾的finally{} 块中显式释放了所有游标,并且在包含它们的类的finalize() 方法中关闭了我的数据库。
我的应用程序的结构使我很难在数据库对象上显式调用 close() 方法(在终结器中除外),因为例如,使用数据库的类不是 Activity 类,而可能是由 Activity 间接使用的类。因此,该类本身并不知道它最终附加到的 Activity 何时被销毁。
我需要关心这个吗?我是否因未显式关闭数据库实例而永久泄漏某些资源?是否存在某些内容无法写入文件的危险? Android 上的 SQLite 实现是否进行写缓存?我可以将其关闭或强制同步吗?
Android VM 关于终结器的策略是什么 - 它们是否保证最终运行?
坦率
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 my 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在我的应用程序中发现了强制关闭问题,这是由于未关闭的连接造成的。就我而言,查询花费了很长时间,用户可以返回到活动并重新单击强制执行新查询。
我只是在调试应用程序时才发现这一点,因为它最终出现了一些我认为在执行时不可能的代码。
只需关闭我的连接即可解决此问题。所以,长话短说,保持整洁总没有坏处。猜猜你无论如何都知道这一点,而你只是在寻找验证?
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?
使用 SQLiteOpenHelper 而不是 SQLiteDatabase,可能会减少一些例外情况。
Using SQLiteOpenHelper instead of SQLiteDatabase, may reduce some of the exceptions.