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;
}