'Global variable in Kotlin (android studio) initialized in one activity remains at initialized value in other activities

I would like to implement a global variable that updates its value when going from one activity to another (and back). To explain in better detail, let's say my variable is called globalVar, and globalVar is initialized in activity A as "", then within activity A, when a couple of buttons are pressed, the value is updated to a new string. When going from activity A to activity B, globalVar at activity B should be equal to the updated string in activity A in addition to some value. In other words, globaVar should be keeping track of its updates.

The problem is that when I'm going from one activity to another, the value of my global variable is resetting itself to its initialized value.

I have already tried making the initialization private, and implementing a public function that updates the value but that didn't work. Below is the code that I have.

public class Speak : AppCompatActivity(){

    private var globalVar= ""

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_speak)

        val pplMom= findViewById<ImageButton>(R.id.pplMom)
         globalVar= "mom" 

       pplMom.setOnClickListener{

        intent= Intent(this, People::class.java)
        startActivity(intent)}} 
        
    public fun setVar (globalVar :String) {

        this.globalVar= globalVar
        Toast.makeText(this, globalVar, Toast.LENGTH_LONG).show()

    }
    public fun getVar(): String {

        return globalVar
    }
}

class People: AppCompatActivity(),  {

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

      
        var mApp= Speak()
        var globalVar= mApp.getVar()
        globalVar= globalVar + "testtest"

        Toast.makeText(this, globalVar, Toast.LENGTH_LONG).show()

}}

What I have printed is "testtest" instead of "Hellotesttest"



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source