'Ionic Capacitor Admob plugin loadAd null object reference

I am developing an Ionic Capacitor app and i am using the capacitor community ad plugin, but i am getting the following error in Android Studio:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference

I am running the application on an android phone with the command ionic capacitor run android -l --external

This is how the error happens:

  • the app opens on the Welcome page
  • the app shows a banner ad
  • i click the login button
  • the app removes the banner ad
  • the app navigates to the login page
  • the app should show a banner ad, BUT the app crashes

Welcome page (login page has the same life cycle methods and calls):

ionViewWillLeave(): void {
  this.removeAd();
}

ionViewWillEnter(): void {
  this.showAd();
}

private async showAd(): Promise<void> {
  await this.admobService.showBanner();
}

private async removeAd(): Promise<void> {
  await this.admobService.removeBanner();
}

Admob service:

public async showBanner(): Promise<void> {
  AdMob.addListener(BannerAdPluginEvents.FailedToLoad, (info) => {
    //console.log(info);
  });

  const options: BannerAdOptions = {
    adId: 'hidden',
    adSize: BannerAdSize.BANNER,
    position: BannerAdPosition.TOP_CENTER,
    margin: 0,
    isTesting: true,
  };
  AdMob.showBanner(options);
}

public async removeBanner(): Promise<void> {
  await AdMob.removeBanner();
}

Admob service is provided in root, and maybe that could be the case? But i would not like to provide it in every page specifically



Solution 1:[1]

Probably, the banner destroys while it trying to show. You can try add a delay via setTimeout (a few seconds for check this idea) for this.showAd(); call:

ionViewWillEnter(): void {
    setTimeout(() => { this.showAd(); }, 3000);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danil Prokhorenko