10
votes

When I start a cursor loader with

 Bundle bundle = new Bundle();
 bundle.putInt("arg", 123);
 getLoaderManager().restartLoader(0, bundle, this);

I want to get the bundle in

 public void onLoadFinished(Loader<Cursor> loader, Cursor data)

But this only seems possible from onCreateLoader(...)

The only workaround I can think of is to subclass CursorLoader and add some fields to persist data across loading to onLoadFinished(...)

Thanks!

2

2 Answers

2
votes

I wouldn't just use a private member field in the class implementing LoaderCallbacks because you never know exactly which loader is finishing. Better to do as the asker suggested and store the data with the loader. Here's how I do it:

public static class CursorWithData<D> extends CursorWrapper {
  private final D mData;

  public CursorWithData(Cursor cursor, D data) {
    super(cursor);
    mData = data;
  }

  public D getData() {
    return mData;
  }
}

@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle bundle) {
  // ...

  return new CursorLoader(getActivity(), uri, projection, selection, args, order) {
    @Override
    public Cursor loadInBackground() {
      return new CursorWithData<Bundle>(super.loadInBackground(), bundle);
    }
  };
}

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
  CursorWithData<Bundle> cursorWithData = (CursorWithData<Bundle>) cursor;
  Bundle args = cursorWithData.getData();
  cursor = cursorWithData.getWrappedCursor(); // Optional if you are worried about performance

  // ...
}
0
votes

Since you are using 'this' as third parameter of onLoadFinished, I assume that the class is implementing the LoaderManager.LoaderCallbacks interface. So there is no need for the parameter, you can use a private member field.