6

Please tell me how to reset the content of ViewPager on android. I tried to call adapter.notifyDataSetChanged() but the adapter doesn't call getItem(position) when I scroll the view. It always returns old child views.

Update: This is my Fragment View. When I reset viewPager data, It used loaded Fragment views. It's just start at the onCreateView instead of Constructor.

public class ResultView extends Fragment {
//Declare properties

     //Constructor 
public ResultView(Province province, Calendar calendar) {
    Log.d("xskt", "ResultView constructor");
    this.province = province;
    this.calendar = (Calendar) calendar.clone();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d("xskt", "ResultView onCreateView");
    View view = inflater.inflate(R.layout.resultview, null);

    //do some thing

    return view;
}

Thanks.

Charles
  • 50,943
  • 13
  • 104
  • 142
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165

4 Answers4

39

I have changed to use FragmentStatePagerAdapter instead of FragmentPagerAdapter, the problem is resolved. Hope this helps.

Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165
  • 1
    I've found a page and published it on Google+ on this. If people are interested in why this fixes it...https://plus.google.com/114575746308111414670/posts/XgVFNVMJcYM – Boy Nov 11 '13 at 18:57
2

I think the best solution to reload fragments in another fragment is :

@Override
public void onPause() {
    super.onResume();
    List<Fragment> fragments = getFragmentManager().getFragments();
    if (fragments != null) {
        FragmentTransaction fragmentTransaction  = getFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            if (fragment instanceof Fragment) {
                fragmentTransaction.remove(fragment);
            }
        }
        fragmentTransaction.commitNowAllowingStateLoss();
    }
}

Check for your use case whether commitNowAllowingStateLoss or commitAllowingStateLoss is necessary.

Michael W.
  • 53
  • 7
Hadi Note
  • 1,386
  • 17
  • 16
0

One method is to use the observer pattern. The data you are presenting is likely in an sqlite DB (or in stored in memory). You can set a listener in your fragment that will make the necessary updates to your fragment when the data is changed.

Patrick Jackson
  • 18,766
  • 22
  • 81
  • 141
0

It works if you do the following:

  • invalidate the viewPager to invalidate the cache
  • call notifyDataSetChanged() to tell the adapter that there have been changes and it has to refresh the Fragments
  • override getItemPosition in your FragmentStatePagerAdapter in order to have all of your Fragments refreshed

In your Activity or wherever you want to refresh the data:

viewPager.invalidate();
fragmentStatePageAdapter.notifyDataSetChanged();

In you FragmentStatePageAdapter:

@Override
public int getItemPosition(@NotNull Object object) {
    return POSITION_NONE;
}