Android getDefaultSharedPreferences
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10786172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android getDefaultSharedPreferences
提问by Kostadin
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.
始终根据操作系统版本返回不同的值。在 2.2、2.3.4、3.2、4.0.3 中测试 - 返回正确值。但是对于带有 2.3.7 和 CianogenMod 7.1 的设备中兴刀片 - 结果总是错误的。我想 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.
更新:将我当前的代码与我以前版本的代码进行比较 - 代码没有区别。唯一的区别在于清单:代码在 minVersion=8 和 targetVersion=8 下可以正常工作现在我正在使用 minversion=8 和 target=13 进行编译/因为 Admob/。也许某些 API 发生了变化,但我对此一无所获。
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.
解决方案: - 从快捷方式和菜单启动应用程序给了我不同的 DefaultSharedPreferences。从我的代码中删除 DefaultSharedPreferences 后 - 它工作完美。我不能只是说:人们不会走捷径,所以我不得不更改代码。
回答by Behzad Momahed Heravi
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:
在这种情况下,您可以指定自己的首选项文件名 (myAppPrefs) 并控制对其的访问权限。其他操作模式包括:
- MODE_WORLD_READABLE
- MODE_WORLD_WRITEABLE
- MODE_MULTI_PROCESS
- MODE_WORLD_READABLE
- MODE_WORLD_WRITEABLE
- MODE_MULTI_PROCESS