Using Shared Preference Change Listener

Updated 26 October 2021

Save

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 :

  1.  Create An Object of the Shared Preference, by calling the getSharedPreferences() method.
  2.  Create a new Object of OnSharedPreferenceChangeListener.
  3. You will need to over ride a default method onSharedPreferenceChanged().
  4. 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.
  5.  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.

sharedPreferenceChangeListener

And you have done it.

Keep coding and Keep Sharing 🙂

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


8 comments

  • Pratheek Adi
    • anchit (Moderator)
  • Pratheek Adi
    • anchit (Moderator)
  • Sinan
    • anchit (Moderator)
  • Huỳnh Cao Minh Tú
    • anchit (Moderator)
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home