Search code examples
androidkotlinandroid-activityadmob

Loading a Rewarded Ad in MainActivity remains null


I am trying to load up a RewardedAd object in MainActivity, then access this object in another activity.

MainActivity:

var rewardedAd: RewardedAd? = null

private fun createAndLoadRewardedAd(adUnitId: String): RewardedAd {
    val ad = RewardedAd(this, adUnitId)
    val adLoadCallback = object : RewardedAdLoadCallback() {
        override fun onRewardedAdLoaded() {
            // Ad successfully loaded.
            println("Ad successfully loaded.")
        }

        override fun onRewardedAdFailedToLoad(adError: LoadAdError?) {
            // Ad failed to load.
            println("Ad failed to load.")
        }
    }
    ad.loadAd(AdRequest.Builder().build(), adLoadCallback)
    return ad
}

And in onCreate(savedInstanceState: Bundle?) I set the value:

rewardedAd = createAndLoadRewardedAd(StaticAppData.rewardedAdID)
println("MAINACTIVITY - $rewardedAd")

On App Load, the print statement has a value set to rewardedAd; it is not null.

Now when I try accessing rewardedAd in another activity (to actually display the rewarded ad), it's null.

addCoinsButtonPressed.setOnClickListener {
    println(MainActivity().rewardedAd)
}

prints `null`.

How can I access the rewardedAd from another activity after it's loaded in MainActivity?


Solution

  • MainActivity() is a constructor, meaning you're trying to access this variable on a new instance.

    To share a variable between activites you can put it in a static context, e.g.

    class MainActivity : Activity {
        companion object {
            var rewardedAd: RewardedAd? = null
        }
    ...
    }
    

    Then access it with MainActivity.rewardedAd.

    Note that while this is a simple solution, global mutable variables are bad practice and should be avoided. Use e.g. a background service instead.