Reputation: 99
I have two activities Main and Settings, So in settings activity, in onDestroy()
override fun onDestroy() {
super.onDestroy()
Log.d("Activity Lifecycle", "onDestroy invoked")
val editor:SharedPreferences.Editor = sharedPreferences!!.edit()
editor.putInt(getString(R.string.SOME_VALUE), this.somevalue!!)
editor.apply()
editor.commit()
Log.d("Editor", "values commited")
setResult(1) // for onActivityResult
}
and in main activity:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d("onActivityResult", "called")
val somevalue = sharedPreferences!!.getInt(getString(R.string.SOME_VALUE),0)
times_2.text = somevalue.toString()
}
and also this in main activity:
override fun onResume() {
super.onResume()
Log.d("Activity Lifecycle", "onResume invoked")
val somevalue = sharedPreferences!!.getInt(getString(R.string.SOME_VALUE),0)
times_2.text = somevalue.toString()
}
so the thing is onActivityResult is called first, then onResume, and then the editor values are commited. I want to refresh parent activity with the updated values
Upvotes: 0
Views: 71
Reputation: 3219
Please do not have any kind of IO operation in onDestroy
. You can make use of onStop
in this case. Also make sure the super constructor gets invoked after you are done with the saving task.
override fun onStop() {
// Do save activity
val editor:SharedPreferences.Editor = sharedPreferences!!.edit()
editor.putInt(getString(R.string.SOME_VALUE), this.somevalue!!)
// editor.apply() // Use this when you want this operation to be async
editor.commit() // Non async save
setResult(1) // for onActivityResult
// Once save is done, call super method to proceed with stop
super.onStop() // Always call after operation
}
Also it is good practice to use .apply()
when you have more number of key value pairs.
Upvotes: 1