Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

sharedpreferences - Android getDefaultSharedPreferences

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...