In my app, the user starts in the MainActivity. When the button (btn) is clicked, an interstitial ad pops up. I want it to go to the SecondActivity when the ad is closed, but it just goes back to MainActivity. I've pasted my code below
class MainActivity : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
val i:Intent = Intent(this, SecoundActivity::class.java)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
var adRequest = AdRequest.Builder().build()
InterstitialAd.load(this, "ca-app-pub-3940256099942544/1033173712", adRequest, object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
mInterstitialAd?.fullScreenContentCallback = object:FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
startActivity(i)
}
}
mInterstitialAd = interstitialAd
}
})
btn.setOnClickListener {
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
}
}
}
}
Any way to solve this. Thanks
Since your mInterstitialAd
is nullable, your FullScreenContentCallback
is never going to be initialized, because mInterstitialAd
is null when you're trying to invoke it. It will be executed before onAdLoaded
will be called.
Put the full screen content callback in the onAdLoaded callback like this
override fun onAdLoaded(interstitialAd: InterstitialAd) {
interstitialAd.fullScreenContentCallback = object:FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
startActivity(i)
}
}
mInterstitialAd = interstitialAd
}
Also it is best practice to put variable initialization to the top of the class instead of the bottom
private var mInterstitialAd: InterstitialAd? = null
private val i = Intent(this, SecondActivity::class.java)