Search code examples
androidkotlinadmobgoogle-ads-api

onUserEarnedReward is never called in Admob 20.1.0


I'm working on converting my Kotlin App to Admob 20.1.0. Running into a problem integrating Rewarded Ads.

The problem is onUserEarnedReward is never called. I currently have no way of rewarding the user with the content they unlocked. My code below is placed in an onClickListener within an AppCompatActivity()

if (mRewardedAd != null) {
    mRewardedAd?.show(this, OnUserEarnedRewardListener { // Redundant SAM-constructor 
        fun onUserEarnedReward(rewardItem: RewardItem) { // Function "onUserEarnedReward" is never used 
            
            val rewardAmount = rewardItem.amount
            val rewardType = rewardItem.type
            println("======================= TYPE -  $rewardType /// AMOUNT - $rewardAmount")
            // This never gets called.
        }
    })
} else {
    println("=======================The rewarded ad wasn't ready yet.")
}

My imports:

import com.google.android.gms.ads.*
import com.google.android.gms.ads.rewarded.RewardItem
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import com.google.android.gms.ads.OnUserEarnedRewardListener

Why am I getting Redundant SAM-constructor and Function "onUserEarnedReward" is never used ?


Solution

  • The reason is you are creating a function in High Order function and not invoking the function. Please try with below code. it will work

           mRewardedAd?.show(this, OnUserEarnedRewardListener { rewardItem ->
            val rewardAmount = rewardItem.amount
            val rewardType = rewardItem.type
            println("======================= TYPE -  $rewardType /// AMOUNT - $rewardAmount")
          }
    

    For your better understanding about high order function below code is also work

       mRewardedAd?.show(this, OnUserEarnedRewardListener { 
        fun onUserEarnedReward(rewardItem: RewardItem) { 
            val rewardAmount = rewardItem.amount
            val rewardType = rewardItem.type
            println("======================= TYPE -  $rewardType /// AMOUNT - $rewardAmount")
        }
        onUserEarnedReward(it)
    })