LoaderManager with multiple loaders: how to get the right cursorloader

AndroidAndroid LoadermanagerAndroid Loader

Android Problem Overview


To me it's not clear how to get the right cursor if you have multiple Loaders. Lets say you define two different Loader with:

getLoaderManager().initLoader(0,null,this);
getLoaderManager().initLoader(1,null,this);

then in onCreateLoader() you do different things depending on the id:

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {
	
	if (id==0){
               CursorLoader loader = new CursorLoader(getActivity(),
			MaterialContentProvider.CONTENT_URI,null,null,null,null);
	}else{
               CursorLoader loader = new CursorLoader(getActivity(),
			CustomerContentProvider.CONTENT_URI,null,null,null,null);
            };
   	return loader;
} 

so far so good. But how to get the right cursor in onLoadFinished() because you don't get any id to identify the right Cursor for the right Cursoradapter.

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		

	mycursoradapter1.swapCursor(cursor);
	if(isResumed()){
		setListShown(true);
	}else {
		setListShownNoAnimation(true);
	}

			

}
//and where to get the cursor for mycursoradapter2

or am I wrong and this is the wrong way to get results for two different cursoradapter in one fragment.

Android Solutions


Solution 1 - Android

The Loader class has a method called getId(). I would hope this returns the id you've associated with the loader.

Solution 2 - Android

Use the getId() method of Loader:

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    switch (loader.getId()) {
        case 0:
            // do some stuff here
            break;
        case 1:
            // do some other stuff here
            break;
        case 2:
            // do some more stuff here
            break;
        default:
            break;
    }
}    

Solution 3 - Android

If your loaders have nothing in common but the class type of the result (here: Cursor), you're better off creating two separate LoaderCallbacks instances (simply as two inner classes in your Activity/Fragment), each one dedicated to one loader treatment, rather than trying to mix apples with oranges.

In your case it seems that both the data source and the result treatment are different, which requires you to write the extra boilerplate code to identify the current scenario and dispatch it to the appropriate code block.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKay GladenView Question on Stackoverflow
Solution 1 - AndroidKurtis NusbaumView Answer on Stackoverflow
Solution 2 - AndroidIgorGanapolskyView Answer on Stackoverflow
Solution 3 - AndroidBladeCoderView Answer on Stackoverflow