CursorLoaders and AsyncTaskLoaders using same LoaderManager

1k Views Asked by At

I have a fragment that uses multiple CursorLoaders. All works fine. Now I need to add an AsyncTaskLoader as well, to the same fragment.

Question is, how can I use the same LoaderManager.LoaderCallbacks interface to manage both my CursorLoaders and AsyncTaskLoader?

My thought is that since CursorLoader is-a AsyncTaskLoader, then I should be able to adapt the LoaderCallBacks to both, but I may be miss the boat...

2

There are 2 best solutions below

2
On

It looks like I am too later for this question, hope it help some guys.

I just finished a project with multi loaders in same Activity, one CursorLoader used for database, other AsynctaskLoaders for network job.

    class YourActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {
    // you still implements LoaderManager.LoaderCallbacks but without add <returnType> 
    //and you have to cast the data into your needed data type in onLoadFinished()

        Private int loader1 = 1;   // eg. CursorLoaderId
        private int loader2 =2;    //eg. AsynctaskLoaderId

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

// init loader with different Id
        getSupportLoaderManager().initLoader(yourLoaderId, null, this);
    }
        @Override
        public Loader onCreateLoader(int id, Bundle args) {
            if (id == loader1 ) {

                //YourLoaderClass1 is you loaderClass where you implement onStartLoading and loadingInBackground() 
                return new YourLoaderClass1();  
            } else if (id == loader2 ) {

                return new YourLoaderClass2();
            }
            return null;
        }

        @Override
        public void onLoadFinished(Loader loader, Object data) {
            int id = loader.getId();// find which loader you called
            if (id == loader1 ) {

                yourMethod1((List< >) data); // eg. cast data to List<String>
            } else if (id == loader2 ) {
                yourMethod1((String) data); // eg. cast data to String
            }
        }

        @Override
        public void onLoaderReset(Loader loader) {
            int id = loader.getId();
            if (id == loader1 ) {

            } else if (id == loader2 ) {

            }
        }
    }

here is my answer under other question and my project link

0
On

This will only work if all the loaders return the same type. If that's true, then you simply need to specify unique ID's for each loader you start. That same ID is passed into the onCreateLoader() call so you just check that ID to figure out which loader to create.