0

I'm trying to show ad When user presses on sound card 10 times but when I press on sound card 10th time no ad is shown and no sound plays anymore until I press stop button after which sound plays again until I press it 10 times again Part of my main activity: ..

    MobileAds.initialize(this,
            "ca-app-pub-2470537820941001~1050614569");

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());

}
    @Override
public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mPowerSaverChangeReceiver);
        if (mSoundPlayer != null) {
            mSoundPlayer.release();
            mSoundPlayer = null;
        }
    }

@Override
public void onResume() {
    super.onResume();
    if (mSoundPlayer == null) mSoundPlayer = new SoundPlayer(MainActivity.this);
}

@Override
public void onPause() {
    super.onPause();
    if (mSoundPlayer != null) {
        mSoundPlayer.release();
        mSoundPlayer = null;
    }
}

this is my sound player class:

class SoundPlayer {

private MediaPlayer mPlayer;
private Context mContext;

private static final String TAG = "SoundPlayer";
private int counter = 0;

private void playSound(Sound sound) {
    int resource = sound.getResourceId();
    if (counter == 5) {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        } else {
            Log.d("TAG", "The interstitial wasn't loaded yet.");
        }

    } else {
        counter++;
    }
    if (mPlayer != null) {
        if (mPlayer.isPlaying())
            mPlayer.stop();
        mPlayer.reset();
       ../

The error

    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.ads.InterstitialAd.isLoaded()' on a          null object reference
at my.app.SoundPlayer.playSound(SoundPlayer.java:38)
at my.app.reactionsounds.SoundPlayer.onEvent(SoundPlayer.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:507)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:501)
at org.greenrobot.eventbus.AsyncPoster.run(AsyncPoster.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
ekor
  • 81
  • 1
  • 7

1 Answers1

0

You have not initialised interstiial Ad in your sound player class.Your error shows clearly that Interstitial ad is null.

                    interstitialAd = new InterstitialAd(ReadingPage.this);
                    interstitialAd.setAdUnitId(getResources().getString(R.string.interstitial1));
                    interstitialAd.loadAd(new AdRequest.Builder().build());
Martin Mbae
  • 1,108
  • 1
  • 16
  • 27