Question

I stumbled across many links on the use of a Cursor object but none about how it is used best. So I have a couple of questions which I would really like answered.

  • Is it okay to use one Cursor for all the application's database operations? If no, why?
  • Is it really necessary to keep opening and closing the Cursors after every use?
  • On this link the definition of close() is Closes the Cursor, releasing all of its resources and making it completely invalid. What happens when it becomes invalid? Would it be re-usable?

Many thanks.

Was it helpful?

Solution

1.)Is it okay to use one Cursor for all the application's database operations? If no, why?

Yes. It is possible to re-use a cursor. However you should know that the working of a Cursor isn't as intuitive as you may think. The cursor doesn't fetch all data from some data store and store all of it in memory. Instead, it only fetches the data as required hence minimizing the memory use. So it is always a good idea to close the Cursor before re-initializing. That being said, there really isn't much performance penalty for creating a completely new Cursor every time you need one.

2.)Is it really necessary to keep opening and closing the Cursors after every use?

Yes, yes and yes. I once had a lot of problems debugging some network application which was to sync activities of the phone periodically to the local db then later send to an external server. Opening and closing (especially closing) is important just like any other stream or endpoint for communication in java or android e.g FileInputStream or Socket

3.)On this link the definition of close() is Closes the Cursor, reusing all of its resources and making it completely invalid. What happens when it becomes invalid? Would it be re-usable?

As I've said above, the close() method works just like most of the other close() methods of other classes in Java. Once you call it, you should not use the Cursor again. This is just like the Socket's class close() method. Once a Socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.

OTHER TIPS

1.Every query returns a new Cursor. So you can use the same local cursor and reinitialize it with returned cursor

2.yes it is necessary to close every cursor. Because some unexpected error/force close can may corrupt your database it is open and also done to free the resources

3.invalid means invalid ... invalid Cursor can't be used or re-used as Selvin sad

Best practice to use cursor is to use loaders(cursorLoader in particular) take a look: https://developer.android.com/guide/components/loaders.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top