0

I am using view pager with 3 tabs in MainActivity of my app to show grid images. I have one MovieFragment for all 3 tabs and I am using FragmentsPagerAdapter to create new instance of MovieFragment everytime tab is changed.

//FragmentsPagerAdapter method
@Override
public Fragment getItem(int position) {
    switch (position){
        case 0: return MoviesFragment.newInstance(buildUrl(Utility.POPULAR_URL));
        case 1: return MoviesFragment.newInstance(buildUrl(Utility.RATED_URL));
        case 2: return MoviesFragment.newInstance("favorite");
        default: return null;
    }
}

//Fragment method
public static MoviesFragment newInstance(String uri){
    MoviesFragment fragment = new MoviesFragment();
    Bundle bundle = new Bundle();
    bundle.putString("fragment", uri);
    fragment.setArguments(bundle);
    return fragment;
}

Now I was getting different results in my app so I debugged this method and I found it calls methods before tab is selected i.e when I open app it creates instances for case 0 and case 1 and when I go to second tab it creates instance for case 2. Now in my second tab when I make changes to database and try to get them in third tab changes are not reflected as it already created instance of third tab when second tab was selected. How do I solve this problem?

f-CJ
  • 4,235
  • 2
  • 30
  • 28
Sahil Shokeen
  • 336
  • 3
  • 22

1 Answers1

0

@Sahil This is because in android ViewPager keeps track of previous and next pages only. So when you initialize the viewPager it automatically create first 2 page and call MoviesFragment for 1st two tab. And once you start scrolling through, it starts keeping the track of only previous and next page.

Read this

hArsh
  • 111
  • 1
  • 10
  • i changed that limit to 0 but still its same behavior – Sahil Shokeen Mar 07 '16 at 14:42
  • @Sahil you can handle your database function through `OnPageChangeListener` by defining a function, as android will always call the immediate next and previous pages. – hArsh Mar 07 '16 at 14:51