Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Async task in viewpager

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

like image 775
Riny Avatar asked Apr 17 '26 18:04

Riny


1 Answers

... 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?
like image 184
dentex Avatar answered Apr 20 '26 21:04

dentex