When should I close a cursor and db?

情到浓时终转凉″ 提交于 2019-12-07 10:01:09

问题


I use the same cursor multiple times in the custom view in its different methods. Should I close the cursor after each use or can I keep it open until the view is destroyed? And the same for the database, can it be opened once the activity that holds this view is created and closed when the activity is destroyed? I continuously receive an error 'close() was never explicitly called on database...' when I do as described above.


回答1:


Should I close the cursor after each use or can I keep it open until the view is destroyed?

Depends. If the cursor result is not going to change meanwhile (e.g. remote connection modifying the DB), then it's OK. Don't forget to use CursorLoader to have Android manage your cursor automatically (e.g. close the cursor if your app crashes).

And the same for the database, can it be opened once the activity that holds this view is created and closed when the activity is destroyed?

Yes, you can open in onResume() and close in onPause() callbacks, or when you know your database is not going to be queried anymore.

I continuously receive an error 'close() was never explicitly called on database...' when I do as described above.

This is normal only if your app crashes. Should not happen if you're doing it like I said above.




回答2:


You would want to close all connections to DB once you don't need them. It's OK to keep connections if you will need them later, i.e. close connection when Activity is to be destroyed.




回答3:


You might try moving your db and cursor code to onResume and onPause to avoid that error. But I imagine a cleaner way altogether would be to implement LoaderCallbacks in your Activity. Have you considered that?



来源:https://stackoverflow.com/questions/12902878/when-should-i-close-a-cursor-and-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!