Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoaderCallbacks as a static inner class (to handle multiple Loaders with different data types returned)

Tags:

android

I have an activity which uses two Loaders. Each of them returns different type of data. To get data from a single Loader one just implements LoaderCallbacks<D> into an Activity. I guess I could just implement LoaderCallbacks<Object> and check the type of the object and then decide which of the two LoaderCallbacks it is, but it seems like a hack to me (mostly because of the lack of type safety here).

So I thought about making the LoaderCallbacks object a static inner class, something like this:

private static class geocoderLoaderCallbacks implements LoaderCallbacks<List<Address>>{

    @Override
    public Loader<List<Address>> onCreateLoader(int arg0, Bundle arg1) {
        GeocoderTask loader = new GeocoderTask(context, "");
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<List<Address>> loader, List<Address> data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLoaderReset(Loader<List<Address>> loader) {
        // TODO Auto-generated method stub

    }


}

And then using lm.initLoader(0, null, geocoderLoaderCallbacks).

Two question arise: is it ok to do, or should I rather stick to implementing LoaderCallbacks into Activity? And how do I safely pass the context into the onCreateLoader? Should I just make a constructor in geocoderLoaderCallbacks and pass the context there like this lm.initLoader(0, null, geocoderLoaderCallbacks(this))?

There is a similar question here LoaderManager with multiple loaders: how to get the right cursorloader but it doesn't explain how to manage two loaders with different data types.

like image 499
Michał Klimczak Avatar asked Mar 20 '12 13:03

Michał Klimczak


1 Answers

It is always ok to move code away from a potentially giant class and it's much cleaner to do it with different classes then with one that can handle everything. You might even want to make them real external classes instead of inner classes if you feel that your Activity has too much code inside. LoaderCallbacks is an interface so you can and mostly should implement it in it's own class.

Passing the Context in the constructor is fine as long as you don't keep static or otherwise cached references to it.

like image 58
zapl Avatar answered Oct 20 '22 23:10

zapl