0

The MainActivity code is

class MainActivity : AppCompatActivity() {
var number=0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    if(savedInstanceState!=null){
     number=savedInstanceState.getInt("Number",number)
    }

    findViewById<Button>(R.id.button).setOnClickListener{
        number +=5
        findViewById<TextView>(R.id.textView).text="$number"

    }





}

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putInt("Number",number)
    Log.i("MainActivity","Saved Instance Called")
}

}

See When I run the app and press back button data of number is not restored however when I press the home button data is restored.

Ryan M
  • 18,333
  • 31
  • 67
  • 74

2 Answers2

2

If you press the home button your app is put in the background and Activity is kept alive (but paused). At any point in time system can destroy it to free up memory and only keep save state bundle created by onSaveInstanceState. This bundle is then passed to onCreate as savedInstanceState when you come back to your app.

However when you press back button your activity is finished and app is closed. There will be no save state generated in this case, so if you want to keep your number value you have to store it in persistent storage like preferences, database, file etc. (depending on use case).

Pawel
  • 15,548
  • 3
  • 36
  • 36
1

You can simply override onSaveInstanceState () method. For more details follow this link. Or else you can override onBackPressed method, store Number's value and then retrieve it again in onResume

Nadeem Shaikh
  • 1,160
  • 9
  • 17
  • 1
    This is incorrect. The back button finishes the Activity, so the instance state won't be preserved. Pawei's (correct) answer expands on this. – Ryan M Feb 05 '20 at 22:27