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 (TestFragment.java) I implement the interface and overrite the testMethod method.

@Override
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();
myInterface.testMethod();

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?

Thanks

Answer

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 {

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


    @Override
    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
        myFragment.onSelectedFilterValue("YOUR_MSG");

        }
        });