Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Bundle args in the onLoadFinished CursorLoader callback

Tags:

android

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!

like image 453
Ian Warwick Avatar asked Apr 29 '12 21:04

Ian Warwick


1 Answers

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

  // ...
}
like image 115
satur9nine Avatar answered Oct 12 '22 12:10

satur9nine