Updated 26 October 2021
In this blog, we will learn about using shared Preference Change Listener.
We know App development is a big task but, there is much fun associated with it. While working on one of the applications, I ran into a situation where I had changed the values of some keys in the Shared preference but if the user back pressed, the changes would not be reflected in the previous activity.
Of course, there are many ways to overcome this situation like overriding the default onBackPressed() method, overriding the onResume() method of the previous activity and then setting the value again and perhaps many more.
But what I needed was something much simpler, like just check one or two keys of a shared preference and fetch the current value of the keys into some views and display them.
When I was traversing through the shared preference functions using the the mighty Ctrl+Space, provided by the Android Studio IDE.
I encountered the registerOnSharedPreferenceChangeListener() method.
I thought of giving this method a try and while trying I found that using this is super easy.
I have more than two activities which are accessing some values stored in shared preferences say A, B , C. Now the user starts with Activity A, goes to activity B and then to C. From Activity C the user changes some value and now the value stored in shared preference has changed.
Now user presses back button and the activity B pops up from the stack and since the views were already created, the views in activity hold the values that were stored in the shared preferences at the time of creation of B, which currently is wrong.
Shared Preference ChangeListener can be very useful in this case.
Changes in the onCreate() method of your activity.
1 2 |
SharedPreferences sharedPreferences = this.getSharedPreferences("My_Shared_Preference_Name",MODE_PRIVATE); sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); |
sharedPreferenceChangeListener
1 2 3 4 5 6 7 8 |
SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals("your_key")){ // Write your code here } } }; |
And you have done it.
Keep coding and Keep Sharing 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
8 comments
https://stackoverflow.com/questions/2542938/sharedpreferences-onsharedpreferencechangelistener-not-being-called-consistently
Your Welcome