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?