I want to save a preference using a Button from an Activity.
My code inside the button listener is:
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE).edit();
editor.putString("key_points", "5"); // value to store
editor.apply();
As I so in some other SO relevant questions, this should work and modify the preference which I called "key_points".
Then, I click my menu button and select "settings".
"settings" starts my SettingActivity in which PreferenceFragment class is called:
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
The PreferenceFragment class is then calling:
addPreferencesFromResource(R.xml.preferences);
The problem is, that the change, I've made to the preference by the Button is not reflected in the PreferenceFragment.
The SettingsActivity is showing the old preference value and not the one I committed.
What is wrong and do I make my SettingsActivity to show the new value of the preference, set by the Button?
Thanks, AJ
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE).edit();
It's probably because you're not using the default SharedPreferences. Preference values are stored into the default one(by default).
Try to use SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
instead of self defined SharedPreferences files.