Search code examples
androidandroid-activitykotlinadmobbanner

How to implement admob banner on multiple activities


I have an app with 2 activities, I used Kotlin. I managed to implement an admob banner with no issues on the main activity, now I want another banner on the second activity, how do I do that. I have searched everywhere but the solutions I get are for implementing the same banner on two activities, but what I want is for each activity to have its own banner. Please note that I am using kotlin not Java, and I have no java experience.

My activity_main.xml looks like this

 <com.google.android.gms.ads.AdView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/adView"
            android:background="@mipmap/ic_launcher_background"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111"/>

My MainActivity.kt looks like this

  super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713")
    adView.loadAd(AdRequest.Builder().build())

When I do the same for the second activity and run the app, the first activity runs and show the ad, now when I move on to the next activity it crashes. how is it done exactly?


Solution

  • The reason you are getting the following error:

    Java.lang.RuntimeException: Unable to start activity ComponentInfo{com.poc.com.eas/com.poc.com.eas.Main2Activity}: 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.
    

    Is because you are trying to call the loadAd() method on the same view you had in your past activity which is no longer active. So what you need to do is define an AdView for your banners on each of the activies and then when you start your Main2Activity you need to call adView2.loadAd(AdRequest.Builder().build())