10

I have a SherlockListFragment that implements a custom AsyncTaskLoader. In the overridden onStartLoading(), I have:

@Override
protected void onStartLoading() {
  if (mData != null) {
    deliverResult(mData);
  }
  else{
    forceLoad();
  }
}

The containing SherlockListFragment initiates the loader in onActivityCreated:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  mAdapter = new MyListAdapter(getActivity());
  setListAdapter(mAdapter);
  getLoaderManager().initLoader(0, null, this);
}

and :

@Override
public Loader<List<MyData>> onCreateLoader(int id, Bundle args) {
  return new MyListLoader(getActivity());
}

The problem is that after 5 activations/navigations to my FragmentActivity, loadinBackground() is not called. The onStartLoding is called, as well as the forceLoad, but that's it. No Exception, nothing in the LogCat.

Any ideas?

Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164

1 Answers1

3

It is Ok to call forceLoad().

See what documentation says:
You generally should only call this when the loader is started - that is, isStarted() returns true.

Full code:

@Override
protected void onStartLoading() {
    try {
        if (data != null) {
            deliverResult(data);
        }
        if (takeContentChanged() || data == null) {
            forceLoad();
        }

        Log.d(TAG, "onStartLoading() ");
    } catch (Exception e) {
        Log.d(TAG, e.getMessage());
    }
}

Important:

documentation says: Subclasses of Loader<D> generally must implement at least onStartLoading(), onStopLoading(), onForceLoad(), and onReset().

AsyncTaskLoader extends Loader but not implements onStartLoading(), onStopLoading(), onReset(). You must implement it by yourself!


P.S. I was confused with it after experience of using simple CursorLoader, I also thought that using forceLoad() is bad practice. But it is not true.

Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
  • You saved my day! You're right, "onStartLoading()" has to be implemented even if it isn't required. Implementing it in my custom AsyncTaskLoader solved my problem. Thanks! – Jeje Doudou Dec 08 '20 at 08:38
  • Being AsycnTask deprecated, I tried AsyncTaskLoader and seems INCREDIBLE that you need to do this unclear tricks to make it work. Thanks. – Val Martinez Aug 20 '21 at 08:30