Search code examples
androidandroid-studiokotlinandroid-savedstate

Saving a variable when exiting an application


I am really new to Android Studio(I just started yesterday) and I'm coding a sort of clicker game(in XML and kotlin). I wanted the click counter (which is in a textview with a text at the begining) to save when leaving the app and loading when launching. I looked up savepreferences but I don't really understand how it works .. Could you guys help me please ?

`class MainActivity : AppCompatActivity() {

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

    val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
    val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
    var mCounter = 0
    var txv = findViewById<TextView>(R.id.tx)
    one.setOnClickListener {
        //Play sound when click
        mp.start()
        //Increment click counter
        mCounter++
        txv.text = "Fixed mistakes:  " + mCounter.toString()
    }
}

}`

Any help is welcomed :)

EDIT: I posted some code that i did with savedpreferences but it is not fully functionnal. I would gladly appreciate some help ^^

EDIT V2: look at the comments for the solution


Solution

  • EDIT V2: I did it, here is the code `class MainActivity : AppCompatActivity() {

    //Counter lateinit initialisation
    var mCounter by Delegates.notNull<Int>()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        //Load la sauvegarde
        loadData()
    
        val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
        val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
        var txv = findViewById<TextView>(R.id.tx)
    
        //ON CLICK
        one.setOnClickListener {
            //Play le son quand on clique
            mp.start()
            //Compteur de click
            mCounter++
            txv.text = "Fixed mistakes:  $mCounter"
            saveData()
        }
    }
    
    private fun saveData() {
        val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
        val editor = sharedPreferences.edit()
        editor.putInt("INT_KEY", mCounter)
        editor.commit()
    }
    
    private fun loadData() {
        val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
        mCounter = sharedPreferences.getInt("INT_KEY", 0)
    }
    

    }`