I am using the support library and am using an AsyncTaskLoader
. Why doesn't the constructor of the AsycTaskLoader
not accepting a Fragment
as a parameter?
I only want the AsyncTaskLoader
to start loading data when it is called or initialized inside my fragments. But as of now, at anytime the Activity goes to onResume
it restarts all the loaders I initialized on different fragments. I believe this is mainly because I am passing fragment.getActivity()
in the constructor of my AsyncTaskLoader instances.
Any way to do this?
So far, I am wrapping the initialization of the loaders in a fragment and each have an inner AsyncTaskLoader, which I customized as well. Then when the fragment is initialized, in the onCreateView
method, I then call the method like so :
initLoader();
initLoader()
method
public Loader<Object> initLoader() {
return getLoaderManager().initLoader(LOADER_ID.DUMMIES, null, new LoaderCallbacks<Object>() {
@Override
public Loader<Object> onCreateLoader(int id, Bundle args) {
Loader<Object> loader = new CustomLoader<Object>(getActivity()) {
@Override
public Object loadInBackground() {
return DummyGenerator.generateDummyEntriesToDb();;
}
};
return loader;
}
@Override
public void onLoadFinished(Loader<Object> loader, Object data) {
setToDb(data);
}
@Override
public void onLoaderReset(Loader<Object> loader) {
}
});
}
CustomLoader.java
- generic implementation I suited to my needs. The releaseResources
method is not filled in but I left it there for future usage.
public class CustomLoader<T> extends AsyncTaskLoader<T> {
T mData;
public CustomLoader(Context context) {
super(context);
}
@Override
public T loadInBackground() {
return null;
}
@Override
public void deliverResult(T data) {
if (isReset()) {
releaseResources(data);
return;
}
T oldData = mData;
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldData != null && oldData != data) {
releaseResources(oldData);
}
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
onStopLoading();
if (mData != null) {
releaseResources(mData);
mData = null;
}
}
@Override
public void onCanceled(T data) {
super.onCanceled(data);
releaseResources(data);
}
public void releaseResources(T data) {
}
}
The generateDummyEntriesToDb
method is working fine just creating list of the objects I am using, as well as the setToDb()
method. The problem is when the activity goes to onResume
the loadnBackground()
method is called again thus I am compelled to think that all the other loaders behave the same way.