【问题标题】:Accessing SharedPreference not working in Android访问 SharedPreference 在 Android 中不起作用
【发布时间】:2013-01-13 03:48:43
【问题描述】:

我有两个活动。在第一个活动中,我将字符串放入共享首选项中。然后我记录 getString ,我看到它出现了。然后我进入第二个活动,我敬酒 getString,我得到了显示的默认值。

第一个活动代码:

SharedPreferences.Editor pref_editor = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE).edit();
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
pref_editor.putString("test", "It works!").commit();
Log.d("XXX", pref.getString("test", "ERRRROR"));

第二个活动代码:

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String current = pref.getString("test", "ERROR");
Toast.makeText(getApplicationContext(), current,
                Toast.LENGTH_SHORT).show();

知道为什么我在敬酒时会得到默认值“ERROR”吗?

【问题讨论】:

  • 日志打印正常吗?
  • 它对我有用。唯一不同的是我的Contexts 是每个 Activity 实例。
  • commit()的返回值是多少?
  • 用getApplicationContext() 也试过了,没问题。我建议清理项目,它可能会做某事。同时从您的测试设备中清除您应用的数据。
  • 卸载了应用程序,然后再次运行。现在它起作用了。啊。谢谢!

标签: java android sharedpreferences


【解决方案1】:

请试试这个:-

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();

【讨论】:

    【解决方案2】:

    您没有在编辑器上调用 commit。在调用提交之前,这些更改是批处理的并且不会写入磁盘。

    【讨论】:

    • OP 正在调用 coomit 参见 pref_editor.putString("test", "It works!").commit();
    【解决方案3】:

    来自this SO post你试过apply()吗?

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多