Sunday 9 February 2014

"Listening" to preference changes

As you already know in an Android app settings, options and user preferences are generally stored using SharedPreferences objects.
The name of the preference file created by PreferenceManager.getDefaultSharedPreferences() is formed by the package name of your app (com.....) plus the suffix _preferences.


What you might not know (at least I didn't know it until I discovered this week while developing my next app) is that Android uses a single instance of the preference file within the same app. This means that if you open the same preference file twice (for example in 2 different Activities) at the same time, every change that you commit using one object (better apply, because the apply() method works asynchronously) will immediately be reflected in the other object.
So, if you change a preference within an Activity you need a method to notify the other components of your app (Activities, Services, etc.), using the same preference file, tha the change has occured.

To do this you have to implement the SharedPreferences.OnSharedPreferenceChangeListener interface within your Activity, Service, etc.
Basically you have to follow the following steps:

1) implement the SharedPreferences.OnSharedPreferenceChangeListener interface, for example:

public class MyExample extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {
...
}

2) register and unregister the listener in the appropriate methods, like onResume and onPause:

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.registerOnSharedPreferenceChangeListener(this);
String currency = pref.getString("currency", "USD");

and (unregister):

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.unregisterOnSharedPreferenceChangeListener(this);

3) override the method onSharedPreferenceChanged in order to listen to preference changes:

@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
   if(key.equals("currency") {
      currency = pref.getString("currency", "USD");
   }
}

Now you know that another component of your app has just changed the value of the currency preference. You may want to perform some actions in response.

3 comments:

  1. Thanks!
    Though, the 'pref' should actually be 'preferences' in the last part.

    ReplyDelete
  2. well explanation about listening to preference changes..Android Training in chennai

    ReplyDelete