I have a class that extends PreferenceActivity and shows the preference screen of my app. Is it possible to check if any changes were made to the preferences?
This helps...
Other related post: SharedPreferences.onSharedPreferenceChangeListener not being called consistently
public class PreferenceClass extends PreferenceActivity {
OnSharedPreferenceChangeListener listener;
public void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = this.getSharedPreferences("settings", 0);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
int flag = 1;
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
super.onCreate(null);
addPreferencesFromResource(R.xml.settings);
}
}
From the official docs:
Reading Preferences > Listening for preference changes
Do
In your
PreferenceActivity
, ie make it a member of yourPreferenceActivity
class and then doregisterOnSharedPreferenceChangeListener(spChanged)
in thePreferenceActivity.onCreate()
method.That's what I do and I never have a problem.
Else it's your conditional checking in the listener that is at fault. Post the code.
EDIT:
From the code you posted, you should make
prefs
a class member variable so it has a global scope.And do
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
instead ofgetSharedPreferences
because you haven't created that file.To create a file you need to use
PreferenceManager
. To get aPreferenceManager
, useActivity.getPreferenceManager()
.In your
PreferenceActivity
class, implement theSharedPreferences.OnSharedPreferenceChangeListener
interface. Add the requiredonSharedPreferenceChanged
method to your class and register it in theonCreate
.See sample code here: