call restartLoader
every time you want fresh data or you want to change your arguments for the cursor.
If you use initLoader
to load data
lm = fragment.getLoaderManager();
lm.initLoader(LOADER_ID_LIST, null, this);
Each call to initLoader
will return the same cursor to onLoadFinished
. The onCreateLoader
method will only be called on the 1st call to initLoader. Hence you can't change the query. You get the same cursor same data to the onLoadFinished
method.
@Override
public void onLoadFinished(
android.support.v4.content.Loader<Cursor> loader, Cursor cursor) {
switch (loader.getId()) {
case LOADER_ID_LIST:
// The asynchronous load is complete and the data
// load a list of
populateFromCursor(cursor);
break;
case LOADER_ID_ENTRY:
populateFromCursor(cursor);
break;
}
// The listview now displays the queried data.
}
So to get new cursor data to onLoadFinished
use restartLoader
and you can pass in bundle info if you want. Below I'm passing null because there's a global variable available.
lm = fragment.getLoaderManager();
lm.restartLoader(LOADER_ID_LIST, null, this);
The loaderManager will then call the onCreateLoaderMethod
.
@Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id,
Bundle args) {
android.support.v4.content.Loader<Cursor> ret = null;
// Create a new CursorLoader with the following query parameters.
switch (id) {
// load the entire list
case LOADER_ID_LIST:
String sortOrder = null;
switch (mSortOrder) {
case 0:
sortOrder = RidesDatabaseHandler.KEY_DATE_UPDATE + " desc";
break;
case 1:
sortOrder = RidesDatabaseHandler.KEY_ID + " desc";
break;
case 2:
sortOrder = RidesDatabaseHandler.KEY_NAME;
}
return new CursorLoader(context, RidesDatabaseProvider.CONTENT_URI,
PROJECTION, null, null, sortOrder);
// load a single item
case LOADER_ID_ENTRY:
sortOrder = null;
String where = RidesDatabaseHandler.KEY_ID + "=?";
String[] whereArgs = new String[] { Integer.toString(lastshownitem) };
return new CursorLoader(context, RidesDatabaseProvider.CONTENT_URI,
PROJECTION, where, whereArgs, null);
}
return ret;
}
Notes: You don't have to call initLoader
you can call restartLoader
every time that is unless you really want the same data that was returned from previous query. You don't have to call onContentChanged()
and in the docs it says the Loader.ForceLoadContentObserver
is done for you.