1

我有两个活动。在第一个活动中,我将字符串放入共享首选项中。然后我记录 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();

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

4

3 回答 3

2

请试试这个: -

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();
于 2013-01-13T04:43:49.320 回答
0

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

于 2013-01-13T03:51:00.853 回答
0

这个SO帖子 你试过apply()吗?

于 2013-01-13T04:27:53.340 回答