Issue
I am trying to show an interstitial ad by calling the bellow function each time a button is clicked from a composable. It works alright for the first click but doesn't get loaded for the next clicks. What am I missing here?
fun loadInterstitial(context: Context) {
InterstitialAd.load(
context,
context.getString(R.string.ad_id_interstitial),
AdRequest.Builder().build(),
object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
mInterstitialAd = null
Log.d("MainActivity", adError.message)
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
mInterstitialAd = interstitialAd
Log.d("MainActivity", "Ad was loaded.")
}
}
)
}
Here is the rest of the interstitial code if necessary.
Thanks for your help!
Solution
Ok from the link pasted in the comment, I got this code:-
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AdNetworkTheme {
Surface(color = MaterialTheme.colors.background) {
AdNetworkApp()
}
}
}
// initialize the Mobile Ads SDK
MobileAds.initialize(this) { }
// load the interstitial ad
loadInterstitial(this)
// add the interstitial ad callbacks
addInterstitialCallbacks(this)
}
}
Clearly, the method being called in the setContent block is the problem.
The setContent block is executed only once until some factor like screen rotation or something to that effect triggers a hundred point recomposition. Now, you are calling the loading method in the setContent. Hence, the ad is loaded for the first time (so you see the logs for the first time). Afterwards, you do not call it anywhere at all. No ads loaded - nothing to show.
You can check this by rotating your screen. The ad will be loaded once more then.
Ok, solution could be to just go ahead and place the loading call in the onClick of the Button itself. I don't think anything else would be necessary.
Answered By - MARSK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.