访问SharedPreference无法在Android中运行

时间:2013-01-13 03:48:43

标签: java android sharedpreferences

我有两项活动。在第一个活动中,我将一个String放入共享首选项中。然后我记录了getString,我看到它出现了。然后我转到第二个活动,我向getString Toast并获得显示的默认值。

第一个活动代码:

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”吗?

3 个答案:

答案 0 :(得分:2)

请试试这个: -

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

来自this SO post您是否尝试过申请()?