-1

i've been searching for hours now, and i can't get a simple interstitial ad to display. the layout is within a fragment and i'm sure that's part of the problem, but i can't find a work around. any help is greatly appreciated - most of what i see is displaying the ad within an activity.

I want the interstitial to appear before the user clicks on a button in an app. i'm sure the issue is with the (this) but I can't find anything.

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("example ad unit");

    mapFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            } else {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(Constants.MAPS_INTENT_URI));
            startActivity(intent);
        }
    });
Neal Simpson
  • 1
  • 1
  • 2

2 Answers2

2

Yes the problem is with the this. Since you are calling it in a Fragment, it won't work. Because this is the constructor from the docs:

public InterstitialAd (Context context)

The constructor requires the context. So change your code like this:

mInterstitialAd = new InterstitialAd(getContext());
Eric B.
  • 4,622
  • 2
  • 18
  • 33
2

To avoid NullPointerException, you can use requireContext()

mInterstitialAd = new InterstitialAd(requireContext());
hery
  • 49
  • 6