Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's different between OnPreferenceChangeListener and OnSharedPreferenceChangeListener

I want to get value of a checkboxpreference. which method is suitable for listen to preference?

And what's real difference between OnPreferenceChangeListener and OnSharedPreferenceChangeListener ?!

UPDATE Why onSharedPreferenceChanged not called?

public class Setting extends PreferenceActivity implements
        OnSharedPreferenceChangeListener // ,OnPreferenceChangeListener
{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);// deprecated warning
    }

    @Override
    public void onSharedPreferenceChanged(
            SharedPreferences sharedPreferences, String key) {// DO Stuff
    }

    @Override
    protected void onResume() {
        super.onResume();
        // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        // PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
        this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        // PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
        this.getSharedPreferences("myPrefDB", MODE_PRIVATE)
                .unregisterOnSharedPreferenceChangeListener(this);
    }
}
like image 411
Dr.jacky Avatar asked Nov 10 '12 11:11

Dr.jacky


1 Answers

The difference between these 2 is that OnPreferenceChangeListener is a callback called only when its preference changes (applies to a single key), while OnSharedPreferenceChange is a callback called whenever any of the preferences in that SharedPreferences object changes (applies to all keys).

So, in your case, you need to use the OnPreferenceChangeListener with your CheckBoxPreference.

Here is an example:

Preference ckboxPref = this.findPreference(CKBOX_PREF_KEY);
ckboxPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference,
            Object newValue) {
        //Do stuff
    }
});

The method findPreference does not work if you use fragments, but you aren't using any so it is fine.

like image 70
Jong Avatar answered Oct 12 '22 08:10

Jong