4

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.

Marcin S.
  • 11,161
  • 6
  • 50
  • 63

3 Answers3

2

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.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
1

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.

  • ok. Any idea from where this error might come from? db is opened in onCreate() and closed in onStop() so how come it still says that it's not closed? – Marcin S. Oct 15 '12 at 20:01
1

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?

newbyca
  • 1,523
  • 2
  • 13
  • 25