Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreferenceManager.getDefaultSharedPreferences() vs getPreferences()

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?

like image 513
fweigl Avatar asked Feb 18 '26 14:02

fweigl


1 Answers

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.

like image 149
Sunil Mishra Avatar answered Feb 21 '26 02:02

Sunil Mishra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!