The problem I have now seems so basic that someone else must have faced it before me.
Here is the code, it just saves some preferences to be used later on:
val editor: SharedPreferences.Editor = sharedPreferences!!.edit()
editor.putString("activeFolder", "FavoriteFolder")
editor.commit()
//finish()
Before that sharedPreferences is declared at the class level like this:
private var sharedPreferences: SharedPreferences? = null
An it is initialized inside onCreate():
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
....
sharedPreferences = getSharedPreferences("MyNiceApp", MODE_PRIVATE)
....
}
After the code is executed I quit the activity by tapping the back button and all is good.
Finally here is the use case causing trouble. In the situation where there is nothing else to do after saving the preferences, instead of having the user manually tapping the back button I want the activity to automatically terninate and for that I call finish() (commented out in the code above). When doing that the activity closes as expected, but for some unknown reason the new preferences are not taken into account.
What do I need to do change to solve this issue?
CodePudding user response:
call this
editor.apply()
you can remove
edit.commit()
CodePudding user response:
I found the issue and learned something at the same time.
I was reading the new value of the sharedPreferences ("activeFolder") inside onCreate() but it appears that the onCreate() of the parent activity is not called after a finish().
Reading the new value of the sharedPreferences inside onStart() instead of inside onCreate() solves the problem.
CodePudding user response:
I cant see any problem from your code, but I guess the code omitted may block your finish action? So you can print some log before and after your finish()
, and see whether it has been executed.