Reputation: 256
I have huge databases (~ 40K rows) which I deal with in my app. There is one activity which has a list view that uses a CursorAdaptor to display and search in the whole database rows. Each time the user deals with a database, I open the database and create the required Cursor and I call Cursor.getCount() in another thread to tackle the laziness issue of cursors and make it fully ready for future operations. It takes around 7 seconds to have Cursor.getCount() done for the huge databases.
Users may invoke this activity multiple times so I store the cursor in a global class as a static data member and I always reuse the same cursor.
I guess that if I did not close the cursor and the database properly I may get weird results. Right?!
My question is: When I should close the cursor and the database?
It will not be possible to close the database and the cursor in Activity.onStop() since I will have to re-open the database and the cursor each time the activity goes from being invisible to visible. And if I did the close in Activity.onDestroy, then the app might be killed by the OS (when device's available memory is low) before the onDestroy is called.
Upvotes: 0
Views: 200
Reputation: 1265
Why don't you turn this global static class into a singleton so that you don't run into instantiation problems, which it sounds like you are referencing. Once you call getInstance() in your singleton you will always get the same cursor and DB connection within that class.
Upvotes: 1