NullPointerException when trying to access views from a Fragment

167 views Asked by At

I basically want to change the visibility of some xml elements in my fragment when the "onRewardedVideoAdRewarded" method in my MainActivity gets called.

Here is the onRewardedVideoAdRewarded method in my MainActivity.java:

 @Override
    public void onRewardedVideoAdRewarded(Placement placement) {

        MyFragment myFragment = new MyFragment();
        myFragment.rewardedVideoFinished();
}

and here is the "rewardedVideoFinished" method of my Fragment:

public void rewardedVideoFinished (){
 
    myButton.setVisibility(View.INVISIBLE);
    ...
}

I'm initializing the button in my fragment's onCreateView method like this:

final View rootView = inflater.inflate(R.layout.tablayout_rewarded,container,false);
myButton = rootView.findViewById(R.id.mybutton);

When the Rewarded Video Ad finishes and the "onRewardedVideoAdRewarded" gets called, the app crashes with the following message:

"java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setVisibility(int)' on a null object reference"

I know what NullPointerExceptions are and I know that "myButton" is not initialized when I call it, but why is this the case? I thought with making a new instance of my Fragment it gets initialized.

How can I fix the problem and make the view in my fragment invisible when the rewarded video ad finishes?

Thanks.

0

There are 0 answers