【问题标题】:Why does preferences.getString("key", "DEFAULT") always return "DEFAULT"?为什么preferences.getString("key", "DEFAULT") 总是返回"DEFAULT"?
【发布时间】:2012-03-06 16:30:04
【问题描述】:

我的 XML 目录中有 user_preferences.xml。 A PreferencesActivity 使用此文件来创建用户首选项活动.. 并且有效。用户在此处选择的任何内容都将持续存在。但我无法检索用户选择的值。

当我使用...

SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);    
String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");

... mapTypeString 始终为“DEFAULT”。

当我实例化我的 SharedPreferences 对象时,似乎找不到我的 user_preferences.xml。但是,PreferencesActivity 当然会找到它。那么,我错过了什么?

非常感谢!

【问题讨论】:

  • 您确定您正在阅读相同的首选项文件吗?
  • 在我的 PreferenceActivity 的 onCreate() 中,我使用 addPreferencesFromResource(R.xml.user_preferences);那么,当我创建 SharedPreferences 对象时,也许我需要以不同的方式指向文件?
  • @SERPRO 有问题,因为 xml 在 xml 目录中?
  • 看看这个问题。它可能对你有用stackoverflow.com/questions/5652682/…

标签: android sharedpreferences listpreference


【解决方案1】:

将您的代码更改为:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);   
 String mapTypeString = preferences.getString("map_type_pref_key", "DEFAULT");

【讨论】:

  • 行得通,谢谢。但我仍然有点困惑......我使用另一个xml,它也将首选项存储在同一个活动中。为什么 getDefaultSharedPreferences 给我 user_preferences.xml 而不是另一个 settings.xml?
【解决方案2】:

您必须在编辑后提交首选项。

SharedPreferences preferences = getSharedPreferences("user_preferences.xml", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("map_type_pref_key", "blah_blah");
editor.commit();

【讨论】:

  • "但我无法检索用户选择的值。"他想找回,而不是改变。
  • 这很可能是问题所在,如果 OP 从未使用 commit() 或 apply() 设置值,则数据将永远无法检索,但需要从问题中进一步澄清跨度>
猜你喜欢
  • 2021-05-18
  • 2016-01-20
  • 2016-07-15
  • 2013-12-07
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2020-10-22
相关资源
最近更新 更多