Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple AsyncTaskLoader in a single activity - does every loader have to be initialized in onCreate?

I have a FragmentActivity with a ViewPager in it - this ViewPager contains three ListViews - each destined to have their own unique adapters (and unique data sets).

I would like to use AsyncTaskLoader to populate these adapters, but ONLY when a given view is selected in the ViewPager.

Is it required to init a loader in the activity's onCreate method? (below code)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_foo);

    getSupportLoaderManager().initLoader(0, null, this);
    getSupportLoaderManager().initLoader(1, null, this);
    getSupportLoaderManager().initLoader(2, null, this);
}

Or is it okay to call call initLoader(...) interactively, such as the result of a listener for OnPageChangeListener.onPageSelected ?

mPager.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int newPage) {
        getSupportLoaderManager().initLoader(newPage, null, this);
    }

    ...
}

I want to avoid having to perform potentially 3 time consuming loaders up front if the user may only ever look at the first view in the pager.

EDIT: Or would it be a better design to have the ViewPager use a Fragment for each view, and each fragment would be responsible for managing its own loader?

like image 731
NPike Avatar asked Nov 17 '11 22:11

NPike


1 Answers

I don't remember the details, but at least with the compatibility library, if you don't call initLoader() from onCreate(), the loader's lifecycle gets messed up, so you might want to call them from onCreate() (might be fixed in the latest version, haven't tested). IIRC, fragments just use the activity's LoaderManager, so loaders are always managed by the activity. Using fragments will generally make your code cleaner, so do migrate to fragments if possible.

like image 52
Nikolay Elenkov Avatar answered Oct 10 '22 20:10

Nikolay Elenkov