I am learning about the Loader
and its implementation with AsynkTaskLoader
.
In many examples I have seen that in the AsynkTaskLoader's onStartLoading
method is where the cache
is checked, and if it is not null the result is delivered directly. However, this method is only called the first time the Loader
is
initiated, since for example when the device configuration changes and the Loader
is initiated again from Activity's OnCreate
method the Loader
call directly onLoadFinished
method.
To better understand the functionally of the Loader
I would like to know how I can recreate a case where the cache is used.
Here some example code:
static class ExampleAsyncTaskLoader extends AsyncTaskLoader<String>{
String mCacheData;
Bundle mArgs;
ExampleAsyncTaskLoader(Context context, Bundle args) {
super(context);
mArgs = args;
}
@Override
protected void onStartLoading() {
/* If no arguments were passed, we don't have a query to perform. Simply return. */
if (mArgs == null) {
return;
}
if (mCacheData != null){
deliverResult(mCacheData);
}else {
forceLoad();
}
}
@Override
public String loadInBackground() {
/* Extract the search query from the args using our constant */
String searchQueryUrlString = mArgs.getString(SEARCH_QUERY_URL_EXTRA);
/* If the user didn't enter anything, there's nothing to search for */
if (searchQueryUrlString == null || TextUtils.isEmpty(searchQueryUrlString)) {
return null;
}
/* Parse the URL from the passed in String and perform the search */
try {
URL githubUrl = new URL(searchQueryUrlString);
return NetworkUtils.getResponseFromHttpUrl(githubUrl);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public void deliverResult(String data) {
mCacheData = data;
super.deliverResult(data);
}
}
In case the Activity is destroyed and recreated (as in configuration change) if the Loader data is ready - you'll receive it via the deliverResult. However, In the case of Activity pause and then resume - the default behavior is to re-fetch the data, This is when the "local cache" makes sense.