bhaskarc
bhaskarc

Reputation: 9521

SharedPreference: OnSharedPreferenceChangeListener not working

Here's my use case.

The PreferenceActivity provides a selectable list of themes. When a user selects a particular theme from the list, I want the effect to take place immediately.

As of now, the change of theme affects all new activities that are launched but it does not affect the currently visible PreferenceActivity and activities on back stack.

To overcome this, I decided to implement a Sharedpreference change listener which on change would clear all old activities from the backstack and restart the same class with the modified theme.

Here's what I tried.

    SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
            SharedPreferences.OnSharedPreferenceChangeListener() {

                @Override
                public void onSharedPreferenceChanged(
                        SharedPreferences sharedPreferences, String key) {
                    Intent newIntent = new Intent(Settings.this,Settings.class);
                    newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(newIntent);

                }

};

I tried simple log message like Log.e("change", "pref changed"); But it seems, this listener is simply not listening for changes.

Upvotes: 0

Views: 454

Answers (1)

user692168
user692168

Reputation:

Register it with SharedPreferences.registerOnSharedPreferenceChangeListener.

Also, keep in mind that the listener is kept in a WeakHashMap. This means that you cannot use an anonymous inner class as a listener, as it will become the target of garbage collection as soon as you leave the current scope. So make your listener an instance variable of your activity or make the activity itself implement the listener.

Upvotes: 2

Related Questions