1

I have a custom AsyncTaskLoader that performs a search based on some query text entered into an ActionBar search:

class SearchLoader extends AsyncTaskLoader<List<String>> {

    private static final String TAG = SearchLoader.class.getName();

    private List<String> data;
    private String query;
    private DataStore dataStore;

    public SearchLoader(Context context, DataStore dataStore, String query) {
        super(context);
        this.dataStore = dataStore;
        this.query = query;
    }

    @Override
    public List<String> loadInBackground() {
        try {
            return dataStore.find(query);
        } catch (SearchException e) {
            Log.e(TAG, String.format("Error performing search, query: %s", query), e);
        }

        return null;
    }
}

I have hooked up an OnQueryTextListener to refresh the loader's data by performing a new search when the query changes:

@Override
public boolean onQueryTextChange(String newText) {
    query = !TextUtils.isEmpty(newText) ? newText : null;
    getLoaderManager().restartLoader(SEARCHRESULTS_LOADER, null, this);
    return false;
}

I am aware that I need to call getLoaderManager().restartLoader.

However, what I am not sure about is how to set the new query text on the loader itself?

  1. I don't have access to the loader instance to call a setter
  2. The arguments of the restartLoader as far as I know are only used if a new loader needs to be created

What is the recommended way to do this?

cweston
  • 11,297
  • 19
  • 82
  • 107

1 Answers1

1

In my experience, restartLoader() causes onCreateLoader() to be called. I don't know why this works, as it seems contrary to what the documentation says about re-using existing loaders. Your code already is passing the saved query instance variable to the loader constructor, so it should do what you want.

This Android sample from Google shows restartLoader() being called when the query text changes.

gnuf
  • 2,722
  • 1
  • 25
  • 32
  • 1
    The private LoaderManagerImpl class has slightly different Javadoc notes for these two methods, that actually better describe what's happening. In particular, for restartLoader(), it says "Call to re-create the Loader associated with a particular ID. If there is currently a Loader associated with this ID, it will be canceled/stopped/destroyed as appropriate. A new Loader with the given arguments will be created and its data delivered to you once available." – gnuf Dec 12 '14 at 19:18