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.
SCENARIO :
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.
APPROACH :
- Create An Object of the Shared Preference, by calling the getSharedPreferences() method.
- Create a new Object of OnSharedPreferenceChangeListener.
- You will need to over ride a default method onSharedPreferenceChanged().
- Check the key name of which you want to monitor and write the code you wish to execute in the body of the onSharedPreferenceChanged() method you just overrided.
- Call the registerOnSharedPreferenceChangeListener() method on the object of the Shared Preference you created.This method takes an object of OnSharedPreferenceChangeListener as input. Pass the object created in step2.
CODE :
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 🙂