Search code examples
androidandroid-cursorloader

Set multiple cursor loaders with multiple adapters - Android


I want to have two cursor loaders in my application fragment. Each one of them has different set of data and is used in different lists.

I found somewhere that with cursor you can use getId() method and then using switch do something. But, there is always method: getLoaderManager().initLoader(0,null,this); after which can be something like this:

adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null, from, to, 0);

This method is only for one cursor, but what if I have adapter1 and adapter2? How can I determine which cursor is for which adapter?


Solution

  • My solution is to implement callback listeners

    public class Query extends  FragmentActivity {//do not implement callbacks
    getSupportLoaderManager().initLoader(Constants.LOADER_DAILY_TASK,
    null,dailyTaskResultLoaderListener);//note listener not "this"
    getSupportLoaderManager().initLoader(Constants.LOADER_OTHER_TASK,
    null,otherTaskResultLoaderListener);//note listener not "this"
    
    private LoaderCallbacks<Cursor> dailyTaskResultLoaderListener
    = new LoaderCallbacks<Cursor>() {   
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bun) {     
            return  new CursorLoader(getBaseContext(),
    Constants.DAILY_TASK_URI,projection, selection,selArgs,null); }
    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
    {...}
    public void onLoaderReset(Loader<Cursor> cursor) {...}};
    private LoaderCallbacks<Cursor> otherTaskResultLoaderListener
    = new LoaderCallbacks<Cursor>() {       
    

    ....I think you get the idea