Search code examples
androidandroid-fragmentsandroid-sqliteandroid-loadermanager

which is right place to open/close database resources in list fragment with Async Task loader


Which is the best place to open and close Database resources in ListFragment which implements LoaderManager.LoaderCallbacks?

I have a list fragment which implements LoaderManager.LoaderCallbacks<Cursor>. Now I init loader in onActivityCreated and in onCreateLoader returned a Loader(MyLoader). The MyLoader class open database resources.then Cursor object returned to onLoadFinished. Here where can i close my opened databse,because we cannot close database before cursor returnted to onLoadFinished.

Many persons said, open database resources in Activity onResume and close in onPause is best.But if i use AsynctaskLoaders how to close the database resources?

I got following error,

close() was never explicitly called on database 'mydb' 
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1849)

Solution

  • You have to close the Cursor after you completed ur operations on Database. Try to make use of common SQLiteOpenHelper(have a look at this) for all the Activities instead of calling Database open/close in every Activity.