Call notifyDataSetChanged() within Fragment

I’m using ViewPager in MainActivity.java with five Fragments.

Now I’ve got a problem.

Running notifyDataSetChanged() works fine like this:

viewpager.getAdapter().notifyDataSetChanged();

But how can I run notifyDataSetChanged() from a Fragment?

I have no idea.

What I’ve tried

Making ViewPager static and then run

 MainActivity.this.viewpager.getAdapter().notifyDataSetChanged() 

doesn’t work.

Add a method to your MainActivity like

public void dataChanged() {
  viewpager.getAdapter().notifyDataSetChanged();
}

and from your fragments call it with

((MainActivity) getActivity()).dataChanged();

You can do this by various methods:

  1. The easiest one – declare a public method in MainActivity.java as following:

    public void onDataSetChanged(){
    if(viewPager != null) {
    viewPager.getAdapter().notifyDataSetChanged()
    }
    }

And then call it from the fragment like this:

((MainActivity) getActivity()). onDataSetChanged();
  1. Using Interface: You can create your own interface as :

public interface OnDataSetChangeListener {
void onDataSetChanged();
}

Declare and define an instance of it in MainActivity.java and then set it to the instance of your fragment. Then call it from fragment as:

onDataSetChangeListener.onDataSetChanged();
  1. Using EventBuses.

And many more.