Naman Vaishnav
Naman Vaishnav

Reputation: 1089

How to update Fragments in ViewPager after updating Adapter?

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;
    }
}

Upvotes: 1

Views: 3458

Answers (3)

Amit Vaghela
Amit Vaghela

Reputation: 22955

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

Upvotes: 2

Tosin Onikute
Tosin Onikute

Reputation: 4002

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);
        }

Upvotes: 1

Gunhan
Gunhan

Reputation: 7035

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

      adapter = new PagerAdapter(getChildFragmentManager());

Upvotes: 2

Related Questions