3

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 :)

Riny
  • 159
  • 1
  • 5
  • 17

1 Answers1

4

... 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.:

  1. ViewPager as a circular queue / wrapping
  2. how to create circular viewpager?
Community
  • 1
  • 1
dentex
  • 3,082
  • 3
  • 25
  • 45
  • -If I call the asynchronous task inside setUserVisibleHint(), wont the async task be called everytime I goto every page ? Wont the user see the loading message all the time on all pages ? – Riny Jun 02 '14 at 10:44
  • Yes. This is way you have to check if it's PENDING (not executed yet). You said you want it to be executed only the first time the user goes to a page. – dentex Jun 02 '14 at 12:16
  • This piece of code is invoked whenever each page becomes visible. Its not executing aysnc task for for first time alone. It executes on each page whenever it turns to visible. if(aTask.getStatus().equals(AsyncTask.Status.PENDING)) { aTask.execute(); } – Riny Jun 04 '14 at 04:57
  • Exactly. I understood this from your Q. But if you want the `AsyncTask` to be executed once and for all the fragments in your viewpager, you should execute it in your container activity's `onCreate` and then pass the data to the fragments. But if you don't post some code to show what you already did, it's all about guessing. – dentex Jun 04 '14 at 08:28
  • Thanks. Saved my problem. – Bobbelinio May 19 '16 at 09:16