I'm implementing LoaderManager.LoaderCallbacks on my MainActivity and I'm overriding onCreateLoader. In the onCreateLoader I simply return a AsyncTaskLoader object, where I override the onStartLoading method, in which I check if the query is null. For this code works, I need to call forceLoad(). Here is a snippet of the code:
@Override
public Loader<String> onCreateLoader(int id, final Bundle args) {
return new AsyncTaskLoader<String>(this) {
@Override
protected void onStartLoading() {
// No need to peform a query if no arguments were passed
if (args == null) {
return;
}
// This needs to be called!!
forceLoad();
}
@Override
public String loadInBackground() {
/* some code */
}
};
}
The problem is that I don't know why I need to call forceLoad(), because its implementation is a "empty" method. In the source code of the Loader Class, the implementation of forceLoad is:
public void forceLoad() {
onForceLoad();
}
and the implementation of onForceLoad() is:
protected void onForceLoad() {
}
I tried to find some methods that override forceLoad() or onForceLoad in the other parts of the code (I use (getSupportLoaderManager().initLoader(arg1, arg2, arg3)), but until this moment have not succeeded. Why do I have to call forceLoad() and why does it work?
The reason Loader class is having empty implementation of onForceLoad() is that Loader is a base class. Their child classes are supposed to be implementing onForceLoad().
If we will see your code, you are using AsyncTaskLoader which basically a child of Loader so AsyncTaskLoader will have the onForceLoad() implementation which is actually this:
@Override
protected void onForceLoad() {
super.onForceLoad();
cancelLoad();
mTask = new LoadTask();
if (DEBUG) Slog.v(TAG, "Preparing load: mTask=" + mTask);
executePendingTask();
}
Your onCreateLoader()basically should be like this:
public Loader<String> onCreateLoader(int id, final Bundle args) {
AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(this) {
@Override
protected void onStartLoading() {
// No need to peform a query if no arguments were passed
if (args == null) {
return;
}
}
@Override
public String loadInBackground() {
/* some code */
}
};
loader.forceLoad(); // This basically gonna run the loader.
return loader;
}