I have a quick question about Cursor use within my Android application.
There are multiple places within my application where I can query the same table for my custom content provider. When I receive the cursor, I parse the data and return a data structure containing the information.
Since this can be done in multiple places in my app, I decided to centralize this work in a utility class so my method would look something like this:
public static String[] getInfoFromCursor(Cursor c)
{
String[] blah = ....
//do work
return blah
}
So I've got 2 questions regarding best practice:
1- Is it a good idea to centralize this work in a utility class or is this a case of unnecessary optimization.
2- Should I be closing both the cursor within the method and the original one used to call said method or is closing it once after this method has returned enough?
Your input is greatly appreciated.
Is it a good idea to centralize this work in a utility class or is this a case of unnecessary optimization
It beats maintaining multiple copies of the code. "Unnecessary optimization" concerns usually crop up more with performance issues (e.g., trying to reduce CPU or heap usage), where sometimes you might be chasing a unicorn in pursuit of savings that aren't worth the effort. Anything you can do to make your app more maintainable usually is a good idea to pursue.
Should I be closing both the cursor within the method and the original one used to call said method or is closing it once after this method has returned enough?
While I am not aware of a problem in closing an already-closed cursor, closing it once will be sufficient. I recommend that you be consistent about where and when you close the cursor, to help you ensure that you indeed are closing the cursor at the right points.