1

I have a query in Kotlin in which a CountDownTimer is running and and the activity goes to a pause state. When it goes to the pause state I'm storing the remaining time of the CountDownTimer in onSaveInstanceState and the timer is stopped using cancel(). Now I want to resume the counter when the activity resumes. But how do I access savedInstanceState inside onResume for knowing the remaining time?

I tried saving the values to a private bundle,

    private var bundle:Bundle?=null
.
.
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        bundle?.putInt("time_left",remaining_time)
    }

    override fun onResume() {
        super.onResume()
        time = bundle!!.getInt("time_left");
    }

.
.

I could have written it in onCreate or using onRestoreInstanceState, but if an activity doesn't go to the onCreate state from onPause state, and directly goes to the onResume state(like when a phone call comes) both onCreate and onRestoreInstanceState will not help. Then how can I update it through onResume?

Vysakh K
  • 21
  • 1
  • 3
  • I think you can store that value in a variable and it will work because Android won't clear your variables until you have low memory or destroyed so in onResume you can use the last updated value or else you can store it in SharedPreference – Manoj Mohanty Mar 31 '20 at 11:45
  • Thank you..I was having the notion that it would get cleared. Since there is no onCreate call it will be preserved. – Vysakh K Apr 02 '20 at 03:40

2 Answers2

0

You're missing in your onCreate

if (savedInstanceState != null) {
    // Load your variable
}

here is a link more detailed: How to use onSavedInstanceState example please

Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • You can't actually, you have to use it in `onCreate` because by definition it is `onCreate(savedInstanceState: Bundle?)` – Biscuit Mar 31 '20 at 11:32
  • but if an activity doesn't go to the onCreate state from onPause state, and directly goes to the onResume state(like when a phone call comes) both onCreate and onRestoreInstanceState will not help. Then how can I update it through onResume? – Vysakh K Mar 31 '20 at 11:51
  • From onstop it can go to onstart without going into on create. Then also what is the way out? – Vysakh K Mar 31 '20 at 12:24
  • From the link in my post : https://stackoverflow.com/questions/6525698/how-to-use-onsavedinstancestate-example-please – Biscuit Mar 31 '20 at 12:57
0

I think if you want to get "time_left", then try and use getIntent().getExtras() in onResume

Anu Bhalla
  • 422
  • 4
  • 11