Home > Enterprise >  Integer Value increase with TextView after Ad Show
Integer Value increase with TextView after Ad Show

Time:06-01

ok I am working on concept idea my dad has pitched to me. I have an app that runs AdMobs. On the interstitial ads based off button. The idea of the app is you press the start button and you watch an ad. However, when the ad is closed out, the value should increase in the Ads Watched Field.

I have created a function that increases the TextView no problem. My issue is with AdMob functions, when I call the function in AdDismissed, it does not change the value. I can plug the function into the Start Button and it increases value, but when the Ad is dismissed it zeros out the textView.

I am showing the demo portion of the app, this is still experimental, but also learning with Admobs and the coding on functions. Any advice would be appreciated. Also the adCounter is in the stop button, that was just to make sure the increments where firing. Which it does work perfectly. My thing is when the ad ends keeping the value.

SO in example the Ads Watched: 167,897,256 should increment by one when the ad is dismissed. However placing adCount() in the dismissed section of the ad does not work it just zeros out that textView.

enter image description here

MainActivity

 import android.content.Intent
 import android.os.Bundle
 import android.widget.Button
 import android.widget.TextView
 import androidx.appcompat.app.AppCompatActivity
 import com.google.android.gms.ads.*
 import com.google.android.gms.ads.interstitial.InterstitialAd
 import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback

 class MainActivity : AppCompatActivity() {



 lateinit var mAdView : AdView
 private var mInterstitialAd: InterstitialAd? = null


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    loadBanner()
    loadInterAd()

    val interAdBtnStart : Button = findViewById(R.id.btnStartAds)
    val interAdBtnStop : Button = findViewById(R.id.btnStopAds)


    interAdBtnStart.setOnClickListener {

        showInterAd()

    }

    interAdBtnStop.setOnClickListener {

      adCountInc()

    }
}



fun adCountInc(){

    val tvAdsAmount : TextView = findViewById(R.id.tvAdsAmount)

    var i : Int = tvAdsAmount.text.toString().toInt()
    tvAdsAmount.text = "${  i}"
}


private fun showInterAd() {

    if (mInterstitialAd != null)
    {
        mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback(){
            override fun onAdClicked() {
                super.onAdClicked()
            }

            override fun onAdDismissedFullScreenContent() {

                super.onAdDismissedFullScreenContent()

                val intent = Intent(this@MainActivity, MainActivity::class.java)

                startActivity(intent)




            }

            override fun onAdFailedToShowFullScreenContent(p0: AdError) {
                super.onAdFailedToShowFullScreenContent(p0)

            }

            override fun onAdImpression() {
                super.onAdImpression()


            }

            override fun onAdShowedFullScreenContent() {
                super.onAdShowedFullScreenContent()

            }

        }

        mInterstitialAd?.show(this)

    }
    else
    {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }
}

private fun loadInterAd() {
    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 = interstitialAd
        }
    })
}

private fun loadBanner() {
    MobileAds.initialize(this) {}

    mAdView = findViewById(R.id.adView)
    val adRequest = AdRequest.Builder().build()
    mAdView.loadAd(adRequest)


    mAdView.adListener = object: AdListener() {
        override fun onAdLoaded() {
            // Code to be executed when an ad finishes loading.
        }

        override fun onAdFailedToLoad(adError : LoadAdError) {
            // Code to be executed when an ad request fails.
        }

        override fun onAdOpened() {
            // Code to be executed when an ad opens an overlay that
            // covers the screen.
        }

        override fun onAdClicked() {
            // Code to be executed when the user clicks on an ad.
        }

        override fun onAdClosed() {
            // Code to be executed when the user is about to return
            // to the app after tapping on an ad.
        }
    }


   }
}

this is the full code to the app so far. Any advice will help. If i place the adCounter() anywhere in the ads section it will not update the textfield at all. Even after the textfield shows 1 then an ad is displayed it will always zero out the text field.

CodePudding user response:

The value is not updated because you are opening the same Activity (MainActivity) on onAdDismissedFullScreenContent again.

First create a global TextView variable like:

private lateinit var tvAdsAmount : TextView`\

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    tvAdsAmount = findViewById(R.id.tvAdsAmount)
    // Other things...
}

Then simply use:

override fun onAdDismissedFullScreenContent() {
    val value = tvAdsAmount.text.toString().toInt()
    // make sure that value is an Integer.
    val updateValue = value  
    tvAdsAmount.text = "$updatedValue"
}

CodePudding user response:

Some points you should learn:

  1. Every time you start a new Activity, you're getting a new TextView that has no memory of what was in a TextView of some previous Activity.

  2. You should never use a UI component like TextView to store application state. It's just not reliable. UI components are intended to be a bridge between your application state and the user. They aren't supposed to be the application state themselves. This is the programming principle of separation of concerns.

  3. Since you're not finishing the previous Activity, you're building up a large stack of duplicate Activities. The user will be surprised when they push the back button to see an outdated copy of the Activity, one after another.

  4. Whenever there's a configuration change (such as a screen rotation, or the user changing some setting in the Android settings like the device language), Android destroys all of the Activities that you have open and creates new instances of them. So any application state you were holding in them is going to be lost. This is why there is a ViewModel class for holding state that will survive configuration changes.

To fix your app:

  1. Change your logic so you aren't starting new Activities. Keep everything in the same Activity instance. If you want to load a new ad, just call the function that loads ads rather than creating a brand new Activity.

  2. Create a ViewModel to hold your application state. In this case, it will just need a LiveData<Int> to hold your count. You can observe this LiveData in your Activity and update the value of the TextView in the observer function. Your ViewModel can have an increment function that increases the LiveData's integer value, and you'll call this after ads are dismissed.

  3. Long term, you can consider backing up this value with SharedPreferences, so the value will persist between sessions of your app.

Points 2 and 3 have many tutorials online and questions on this site about them, so I'm not going to explain them in detail.

  • Related