Android getDefaultSharedPreferences

AndroidSharedpreferences

Android Problem Overview


My code is:

final String eulaKey = "mykey";
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean hasBeenShown = prefs.getBoolean(eulaKey, false);

Always returns different values depending on os version. Tested in 2.2, 2.3.4, 3.2, 4.0.3 - returns correct value. But for device Zte blade with 2.3.7 with CianogenMod 7.1 - result is always false. I suppose default value for getBoolean.

Here is code writing boolean:

final String eulaKey = "mykey";
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(eulaKey, true);
editor.commit();

Does anybody have any idea?

Update: Comparing my current code with my previous version of code - there is no difference in code. Only difference is in manifest: code works Ok with minVersion=8 and targetVersion=8 Now I'm compiling with minversion=8 and target=13 /because of Admob/. Maybe some APIs changed, but I found nothing on this.

SOLUTION: -Starting app from shortcut and from menu gives me different DefaultSharedPreferences. After removing DefaultSharedPreferences from my code - it works perfect. I can't just say: people don't make shortcuts, so I had to change code.

Android Solutions


Solution 1 - Android

Try it this way:

final String eulaKey = "mykey";
Context mContext = getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(eulaKey, true);
editor.commit();

in which case you can specify your own preferences file name (myAppPrefs) and can control access persmission to it. Other operating modes include:

  • MODE_WORLD_READABLE
  • MODE_WORLD_WRITEABLE
  • MODE_MULTI_PROCESS

Solution 2 - Android

If you've upgraded to targeting API 30 drop this in your gradle dependencies:

implementation 'androidx.preference:preference-ktx:1.0.0'//For Kotlin Projects

implementation 'androidx.preference:preference:1.1.1'//For Java Projects

After re-synching Gradle change all of your imports from

import android.preference.PreferenceManager

To

import androidx.preference.PreferenceManager

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKostadinView Question on Stackoverflow
Solution 1 - AndroidBehzad Momahed HeraviView Answer on Stackoverflow
Solution 2 - Androiduser2288580View Answer on Stackoverflow