Reputation: 159
I am using FragmentStatePagerAdapter to set ViewPager content. In getItem() method of the adapter, I invoke a fragment. I want to display product images and names dynamically from server on each view pager fragment. I am calling the async task in OnCreateView() of the fragment. But the async task for adjacent products are also invoked. I want to know which is the best way to do this ?
Should I perform async task well ahead and set the adapter of view pager? If its so, I have 1000s of products, It will take huge time to set the adapter.
Or Should I perform async task after every page has loaded? But here, every time I come to the page, it keeps loading data from server. I want the data to be loaded only first time I visit the page, on next swipe, it should display simply instead of fetchng from server again.
I would also like this to be as an infinite view pager adapter, how is this possible ?
Many thanks in advance :)
Upvotes: 3
Views: 3193
Reputation: 3263
... I want the data to be loaded only first time I visit the page, on next swipe, it should display simply instead of fetchng from server again.
Move your AsyncTask
call from OnCreateView
to setUserVisibleHint
: will be executed when the fragment will be visible to the user:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// launch your AsyncTask here, if the task has not been executed yet
if(aTask.getStatus().equals(AsyncTask.Status.PENDING)) {
aTask.execute();
}
}
}
... I would also like this to be as an infinite view pager adapter, how is this possible ?
This has already been answered, i.e.:
Upvotes: 4