1

I am trying to wrap my head around the proper use of fragments with the ViewPager. I currently have 5 fragments (with one main activity) each of which pulls some data from a web service and displays it to the user. The user can swipe between the views to see the different info. The problem I am running into is the fragments get destroyed and recreated once the user swipes two pages away and then back to the fragment resulting in multiple calls to the web services when they are not needed. Configuration changes also force the fragments to be recreated (thus recalling the webservice). I am currently recreating a new instance of the fragment every time. Whats the best way to cache the data? Or am I using FragmentPagerAdapter in the wrong way? I've attached some relevant code.

 @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                WebFragmentOne a = WebFragmentOne.newInstance();
                return a;

            case 1:
                WebFragmentTwo b = WebFragmentTwo.newInstance();
                return b;

            case 2:
                WebFragmentThree c = WebFragmentThree.newInstance();
                return c;

            case 3:
                WebFragmentFour d = WebFragmentFour.newInstance();
                return d;

            case 4:
                WebFragmentFive f = WebFragmentFive.newInstance();
                return f;
        }
        return null;
    }

The newInstance() method in each of the fragments.

public static final WebFragment newInstance()
{
    WebFragment f = new WebFragment();
    return f;
}
IZI_Shadow_IZI
  • 1,921
  • 4
  • 30
  • 59
  • 1
    http://stackoverflow.com/questions/18544698/viewpager-retaing-old-fragments-on-screen-rotation check the link for the other part "onSaveInstanceState()".. u control the lifecycle and what state to save/restore when there is orientation change... no need to return to network to get data again... – Robert Rowntree Dec 13 '13 at 22:13

1 Answers1

1

Keep the data you want to keep in a private field within the fragment.

In the OnCreate call setRetainInstance(true) to stop Android destroying your fragment.

Now you can check when the fragment starts if you already have data. If you don't then you can retrieve it from your web service. If you do then skip the retrieval and jump straight to the setting up of your views.

Kuffs
  • 35,581
  • 10
  • 79
  • 92