1

I call loadCategory method from different items of navigation drawer. On the first call ViewPager load the correct data. But on the second call data doesn't change. ViewPager shows the old data, Please help.

Thanks in advance.

    private void loadCategory(int id) {
          toolbar.setTitle(categoryList[id]);
          adapter = new PagerAdapter(getSupportFragmentManager());
          mViewPager.setAdapter(adapter);
          adapter.notifyDataSetChanged();
    }

    public class PagerAdapter extends FragmentPagerAdapter{

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    @Override
    public Fragment getItem(int position) {
        Bundle bundle = new Bundle();
        bundle.putString("shayari",currentShayaaris[position]);
        Fragment SFragment = new ShayariFragment();
        SFragment.setArguments(bundle);
        return SFragment;
    }

    @Override
    public int getCount() {
        return currentShayaaris.length;
    }
}
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
Naman Vaishnav
  • 1,069
  • 1
  • 13
  • 24

3 Answers3

2

If you are inside a fragment you should instantiate adapter like this

      adapter = new PagerAdapter(getChildFragmentManager());
Gunhan
  • 6,807
  • 3
  • 43
  • 37
2

There are several ways to update

When using FragmentPagerAdapter or FragmentStatePagerAdapter,

if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.

check this link for more information.Update ViewPager

Override getItemPosition in your PagerAdapter

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

second way to update viewpager

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
1

You might need to removeView and addView to reload your viewpager to get new changes in your loadCategory function after updating adapter.

        ViewGroup parent = (ViewGroup) mViewPager.getParent();
        if (parent != null) {
            parent.removeView(mViewPager);
            mViewPager.getAdapter().notifyDataSetChanged();
            parent.addView(mViewPager);
        }
Tosin Onikute
  • 3,883
  • 6
  • 38
  • 61
  • when i call loadCategory method second time, it changes data on next to next fragment. But the current fragment still show data. – Naman Vaishnav Jan 08 '16 at 12:50
  • actually, you are not suppose to call the adapter = new PagerAdapter(getSupportFragmentManager()); every time you want to update the adapter. You are only suppose to just remove the view, notiffyDataSetchanged and add the view back – Tosin Onikute Jan 08 '16 at 12:59