android sharedpreferences set value

davs picture davs · Jul 25, 2010 · Viewed 40.7k times · Source

I have preferences page. It has field 'Show info screen' (as checkbox).

I have also info page which also should have checkbox 'Show me again'.

As I've understand, I can get value from preferences page via PreferencesManager.getDefaultPreferences(context) ...

But how I should set preferences value for the checkbox on info page?

I tried to use context.getSharedPreferences(PREF_NAME, 0).edit(), to set value but it doesn't correlate with PreferencesManager's corresponding value.

What should I do??? F1

Answer

Stephen Denne picture Stephen Denne · Jul 25, 2010

It depends on whether you are after one set of preferences for your application, or one set per activity.

I've used code like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putBoolean(PREF_NAME, false);
editor.commit();

and

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
if (prefs.getBoolean(PREF_NAME, true)) {
    // etc
}