I'm using Android Compatibility Library in my project. I've set up ListFragment as described in the DevGuide (http://developer.android.com/reference/android/app/Fragment.html), and using a simple CursorLoader Christian made be used without content provider (CursorLoader usage without ContentProvider).
The question is where, in my ListFragment / parent Activity, should I open database, return the Cursor, create Adapter and setListAdapter?
So in my app, I have TitlesFragment, DetailsFragment, FragmentLayoutActivity, DetailsLayoutActivity.
Is the best practice...
to open database in ListFragment's onActivityCreated
and close it in ListFragment's onDestroy
like in code sample below
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Open database
playersDatabaseHelper = new PlayersDBAdapter(getActivity());
playersDatabaseHelper.open();
getLoaderManager().initLoader(0, null, this);
...
}
@Override
public void onDestroy() {
super.onDestroy();
if (playersDatabaseHelper != null) {
playersDatabaseHelper.close();
}
}
query database and return the cursor in onCreateLoader
, and create the Adapter and setListAdapter in onLoadFinished
like in code sample below
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new MyCursorLoader(getActivity()) {
@Override
public Cursor loadInBackground() {
playersCursor = playersDatabaseHelper.getAllPlayers();
return playersCursor;
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Create an empty adapter we will use to display the loaded data.
playersAdapter = new RowAdapter(getActivity(), playersCursor, R.layout.players_overview_row);
// Allocate the adapter to the List displayed within this fragment.
setListAdapter(playersAdapter);
playersAdapter.swapCursor(cursor);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
Am I on the right track or should I move some of those somewhere? Thanks for your time!
Sorry no experience in CursorLoader yet and Fragment, but I already experienced use of SQLiteOpenHelper in the context of concurrent access by different threads & activities.
I will assume that PlayersDBAdapter is internally using a SQLiteOpenHelper class. but it is not clear what your methods open() and close() are doing?
What I did:
At least this works, no crashs in an application with several thousands users. Suggestions to improve that are welcome :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With