How to use interface to communicate between fragment and activity?

I simply want to call a Fragment method from my MainActivity.

So I tried to use an Interface.

public interface MyInterface {
        void testMethod();

In my Fragment ( I implement the interface and overrite the testMethod method.

public void testMethod() {
    Toast.makeText(getActivity(), "Test", Toast.LENGTH_LONG).show();

but now I want to call this method from my MainActivity as soon as the onRewardedVideoCompleted get’s called, but I’m not sure how to do it. I tried it like this:

MyInterface myInterface = new TestFragment();

But here I get an nullPointerException:

Attempt to invoke virtual method ‘java.lang.String android.content.Context.getPackageName()’ on a null object reference Which reffers to the Toast message.

How do I call the method from my Interface in my MainActivity without getting an NullPointerException?



You need to create the interface for it like below

public interface FilterValuePassInterface {

    public void onSelectedFilterValue(String name);

Fragment class should look like below

class MyFragment extends Fragment implements FilterValuePassInterface {

    public void onAttach(@NonNull Context context) {
        try {
            ((YOUR_ACTIVITY) getActivity()).setOnDataListener(this);
        } catch (Exception ex) {

    public void onSelectedFilterValue(String name) {


And inside the Activity class , you need to create the method setOnDataListener and initialise the fragment like below

 MyFragment myFragment;
    public void setOnDataListener(MyFragment myFragment) {

    this.myFragment = myFragment;


Again inside the activity you can send the data from any click or event, you just need to call this method from the activity to transfer the data in fragment like below

    YOUR_CLICK.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {
        // TODO Auto-generated method stub