Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify other activity of a preference changed

Tags:

java

android

I'm trying to have the main activity notified of a change in preferences in the PreferenceActivity but the onSharedPreferenceChanged is not firing when I change the preference.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener()
    {   
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
        {
            Log.d("Dict", "PreferenceChanged: " + key);
        }
    });
like image 983
piotr Avatar asked Feb 18 '23 04:02

piotr


2 Answers

My guess is (because it's a common mistake) that you are registering the listener in onResume() and unregister it in onPause(). That will prevent the listener from firing. If that's what's happening, changing your code to register during onCreate() and unregister during onDestroy() will fix the problem.

like image 165
Ted Hopp Avatar answered Feb 20 '23 18:02

Ted Hopp


You can use this code Find the what Preference current value change according to his key

public class SharedPreferences implements OnSharedPreferenceChangeListener {

@Override
public void onSharedPreferenceChanged(
        android.content.SharedPreferences sharedPreferences, String key) {
    // TODO Auto-generated method stub

    sharedPreferences.getBoolean(key, defValue);
    sharedPreferences.getFloat(key,defValue);
    sharedPreferences.getInt(key, defValue);
    sharedPreferences.getString(key, defValue);
    sharedPreferences.getString(key, defValue);
}

}

like image 38
Mohd Saleem Avatar answered Feb 20 '23 19:02

Mohd Saleem