2
PreferenceManager.getDefaultSharedPreferences(context)

and

getPreferences()

seem to retrieve different Preferences.

PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
                        "userWasAskedToEnableGps", false);

for me returns false,

getPreferences(MODE_PRIVATE).getBoolean("userWasAskedToEnableGps", false);

returns true.

The Preference was written with an Editor like

Editor e = getPreferences(MODE_PRIVATE).edit(); 
e.putBoolean (...);
e.commit();

How can I get the same Preferences outside of an Activity from the Context?

fweigl
  • 21,278
  • 20
  • 114
  • 205

3 Answers3

13

According to the docs

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.

getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name. scope limited to activity where it is created

So if you want the preference to be available in another activity or context, you have to use either of getSharedPreferences() or getDefaultSharedPreferences()

This ans explains you the difference between the two.

Community
  • 1
  • 1
Sunil Mishra
  • 3,796
  • 1
  • 27
  • 40
9

From android github repo(1), we can see that getPreferences does nothing other than invoking getSharedPreferences method with current class name.

public SharedPreferences getPreferences( int mode ) {
    return getSharedPreferences( getLocalClassName(), mode );
}

There is nothing limiting other activities/code from accessing the shared preference with appropriate class name. More importantly, I prefer not to use getPreferences, since that implies => never ever change the Activity name. If you change, then take care of the accessing shared preferences with explicit mentions to the earlier class name ( before upgrade ).

kiranpradeep
  • 10,859
  • 4
  • 50
  • 82
1

Use Context.getSharedPreferences with the same constant name and it will give you the same preferences in any point of your app.

Maxim Efimov
  • 2,747
  • 1
  • 19
  • 25