0

The code:

private fun initAds() {
    val adRequest = PublisherAdRequest.Builder().build()
    pavDetail.loadAd(adRequest)
    pavDetail.adListener = object : AdListener() {
        override fun onAdLoaded() {
            super.onAdLoaded()
            pavDetail.visibility = View.VISIBLE
        }

        override fun onAdFailedToLoad(i: Int) {
            pavDetail.visibility = View.GONE
            super.onAdFailedToLoad(i)
        }
    }
}

pavDetail is com.google.android.gms.ads.doubleclick.PublisherAdView and I get it by kotlinx synthetic from XML layout.

This code sometimes throws IllegalStateException because pavDetail mysteriously becomes null in onAdLoaded & onAdFailedToLoad.

I made it pavDetail?.visibility to prevent the crash but I am not sure this will work because I am suspicuous that calling pavDetail itself may throw that exception. Remember this is not NullPointerException this is a IllegalStateException giving message pavDetail must not be null.

Hence, I ask why pavDetail becomes null and how to prevent the crash.

Egemen Hamutçu
  • 1,602
  • 3
  • 22
  • 34
  • do you use it in a `ViewHolder`? – Andrei Tanana Oct 16 '19 at 09:28
  • `initAds` method called by `onChanged` method of `ViewHolder` if there is no data. If there is data, it is called by `onActivityCreated` in a `Fragment` – Egemen Hamutçu Oct 17 '19 at 08:06
  • Do your `ViewHolder` implements `LayoutContainer`? – Andrei Tanana Oct 17 '19 at 09:39
  • Sorry I mixed your question by seeing `ViewHolder` as `ViewModel`. This code is in a `Fragment` which is a `ViewPager` item, so it does't use `ViewHolder`. Hence, `initAds` method called by `onChanged` method of `ViewModel` if there is no data in `LiveData`. If there is data, it is directly called by `onActivityCreated`. – Egemen Hamutçu Oct 18 '19 at 10:48

0 Answers0