Search code examples
androidandroid-asynctaskandroid-viewpagerandroid-pageradapter

When to call AsyncTask in Fragments in a ViewPager?


I have a ViewPager of fragments.
For each fragments, in the onCreateView(), I use AsyncTask to query the server.
I create the fragments in FragmentPagerAdapter's getItem().
However, because getItem() method will be called for the visible fragment and also the adjacent fragments, I am calling the onCreateView() and thus the AsyncTask of the adjacent Fragment even though the fragment is not visible.
How do I only call the AsyncTask of the visible fragment?

Is using onPageSelected() for the ViewPager the correct solution?
I used this method to call AsyncTask instead of in onCreateView() but then the onCreateView() of the fragment is not called.

Thank you.


Solution

  • You could override the method of Fragment:

    setUserVisibleHint(boolean isVisibleToUser) {
         super.setUserVisibleHint( isVisibleToUser);
         if(isVisiableToUser) {
         }
    }