NPike
NPike

Reputation: 13254

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?

Upvotes: 6

Views: 2355

Answers (2)

Bostone
Bostone

Reputation: 37126

Since you are using Fragments already I would suggest to use Fragments in your view pager. I do and it works much better. Then indeed you will initialize one loader per fragment. If these fragments are related you can define abstract extension and put common initialization logic there, then you can extend that to create a concrete fragment

In your code above I found out that initialization of each subsequent loader will cancel the execution of the previous one even the IDs are different

Upvotes: 1

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

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.

Upvotes: 1

Related Questions