androidfacebook-audience-network

How to call only onAdloaded on Facebook Native Ads using normal Adlistener call all override


Please help me come up with a method where I can shorten the native ad code as it gets really confusing if I use more than one ad

try {
                    fbNativeAd = NativeAd(this@SplashActivity, fbNative)
                } catch (e: Exception) {
                }

                val nativeAdListener: NativeAdListener = object : NativeAdListener {
                    override fun onMediaDownloaded(ad: Ad) {
                        // Native ad finished downloading all assets
                        Log.e(TAG, "Native ad finished downloading all assets.")
                    }

                    override fun onError(ad: Ad, adError: AdError) {
                        // Native ad failed to load
                        Log.e(TAG, "Native ad failed to load: " + adError.errorMessage)
                    }

                    override fun onAdLoaded(ad: Ad) {
                        // Native ad is loaded and ready to be displayed
                        Log.d(TAG, "Native ad is loaded and ready to be displayed!")
                        inflateFbNativeAd(fbNativeAd!!)
                    }

                    override fun onAdClicked(ad: Ad) {
                        // Native ad clicked
                        Log.d(TAG, "Native ad clicked!")
                    }

                    override fun onLoggingImpression(ad: Ad) {
                        // Native ad impression
                        Log.d(TAG, "Native ad impression logged!")
                    }
                }

                // Request an ad
                try {
                    fbNativeAd!!.loadAd(
                        fbNativeAd!!.buildLoadAdConfig()
                            .withAdListener(nativeAdListener)
                            .withMediaCacheFlag(NativeAdBase.MediaCacheFlag.ALL)
                            .build())
                } catch (e: Exception) {
                }

This is the code I'm using right now, how can I shorten it? Should I try to use Abstract listener? because when I did try to use it, it did not work. Can anyone please show me what I'm doing wrong?


Solution

  • I can understand your problem. Same problem with me. Facebook sdk is not smart/flexible as comapred to Admob.

    In Facebook-Audience-Network: You can not call single method of AdListener like onAdLoaded if you call single method then code will not work, You must be call all methods then it works.

    You can shrink/short code in this way:

    LONG CODE:

    override fun onMediaDownloaded(ad: Ad) {
                            // Native ad finished downloading all assets
                            Log.e(TAG, "Native ad finished downloading all assets.")
                        }
    

    Short this useless code(in this way):

    override fun onMediaDownloaded(ad: Ad) {}
    

    Thanks

    Happy Coding:)