3

I wanna display a dialog when the user selects a specific item from a ListPreference in my preferenceActivity. But, I cannot get the onSharedPreferenceChanged() to work. I've put a Toast in the beginning of the method, and it does not show, so the method doesn't even run through, why is this?

Here's my code: (Thanks)

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {

    Toast.makeText(Preferences.this, "prefs Changed", Toast.LENGTH_SHORT)
            .show();

    if (key.equals("boolean_ad_type")) {

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String value = sharedPreferences.getString("boolean_ad_type", "");
        if (value != null && value.equals("Pop-up Ads")) {

            Toast.makeText(Preferences.this, "Pop-up Ads Selected",
                    Toast.LENGTH_SHORT).show();
        }

    }
}

And do I need to implement it in the activity like this? (I've tried with and without, no difference)

    public class Preferences extends PreferenceActivity 
                  implements OnSharedPreferenceChangeListener {
Jakob Harteg
  • 9,587
  • 15
  • 56
  • 78
  • possible duplicate of [SharedPreferences.onSharedPreferenceChangeListener not being called consistently](http://stackoverflow.com/questions/2542938/sharedpreferences-onsharedpreferencechangelistener-not-being-called-consistently) – Mr_and_Mrs_D Dec 21 '13 at 16:17

2 Answers2

8

onSharedPreferenceChanged not fired if change occurs in separate activity?

public class MyActivity extends PreferenceActivity implements
    OnSharedPreferenceChangeListener {

@Override
protected void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    // Unregister the listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
}
Community
  • 1
  • 1
agamov
  • 4,407
  • 1
  • 27
  • 31
0

you have to set a click listener for that specific preference you want to show the dialog in your onCreate

PreferenceScreen ps2 = (PreferenceScreen) findPreference("ic_vol");
    ps2.setOnPreferenceClickListener(this);
tyczj
  • 71,600
  • 54
  • 194
  • 296