Search code examples
androidandroid-fragmentsandroid-loadermanager

Multiple fragments with different loadermanager


I am fairly new to android development and have been searching for the solution for the past 4 hours.

I have 2 Fragments in an Activity and both of them uses different sqlite tables for data which will then be put into adapters to show within the fragment.

I'm using Loader manager created two different loaders (with different Ids) for two fragments. I'm defining Loader callback functions in each fragment. The problem is when I load the data using one fragment, in OnCreateLoader of that fragment return null data for the second Fragment.

here is the code I've implemented in one fragment:

    @Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (id==1){
        String[] projection = {
                NoticeTable.COLUMN_ID,NoticeTable.COLUMN_TITLE
        };
        CursorLoader cursorLoader = new CursorLoader(this,
                NoticeContentProvider.ALL_NOTICE_URI, projection, null, null, null);
        return cursorLoader;
    }
    else{
        return null;
    }
}

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

    switch (loader.getId()) {
        case 1:
            adapter.swapCursor(data);
            break;
        case 0:
            break;
    }
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    switch (loader.getId()) {
        case 1:
            adapter.swapCursor(null);
            break;
        case 0:
            break;
    }
}

Solution

  • If you put all of your LoaderManager functions inside each Fragment, you shouldn't have a problem. The setup would be like this:

    public class FragOne extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {}
    public class FragTwo extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {}
    

    Then, you can initialize the loader inside the Fragment's onResume or something like that, so it'll work independently of the other Fragment.

    I would like to add as a suggestion to use a constant variable for the loader id. I tend to do so like this:

    public class FragOne extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
       private static final int FRAG_ONE_LOADER = 0;
    
       public void onLoaderReset(Loader<Cursor> loader) {
          switch(loader.getId()) {
             case FRAG_ONE_LOADER:
                doStuff();
                break;
             default:
                break;
          }
       }
    }
    

    Since you've separated the logic into each fragment, FragmentOne will never see or have access to a loader with id FRAG_TWO_LOADER.