When the viewpager is restarted, it keeps executing the previous fragment

The activity has a homeFragment that contains a viewPager.

If I refresh the homeFragment, the viewPager is also regenerated with the new data.

But The old fragment in the viewPager is re-executed before the adapter is created.

I do not get a clear answer even if I googleing it

1. homeFragment refresh code :

Fragment currentFragment = null;
currentFragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();


2. adapter

public class ChartViewPagerAdapter extends FragmentStatePagerAdapter {

   public ChartViewPagerAdapter(FragmentManager fm) {

   public Fragment getItem(int i) {
      ChartFragment chartFragment = new ChartFragment();
      Bundle args = new Bundle();
      args.putInt("POSITION", i);

      return chartFragment;
      //return ChartFragment.newInstance(i);

   public int getCount() {

       switch (MainActivity.countryCode) {
          case "US":
            return 4;
          case "KR":
            return 3;
          case "DE":
            return 3;
          case "JP":
            return 1;
          case "CN":
            return 1;
          case "HK":
            return 1;
          case "FR":
            return 3;
          case "GB":
            return 2;
            return 3;
  1. The closest approach is when executing viewpager.setSaveParentEnlaled (false); but If I see the log record, it will be called again same code several times, so I get error message.

  2. It is not a problem If I change the refresh method to run the method in the homeFragment immediately without using detach / attach way, but the design should use the detach / attach way.

1 answer

  • answered 2019-04-15 06:27 Abdur Rahman

    You must call the


    or in kotlin

    viewpager.adapter = (null)

    It will be reset the ViewPager to start position.