Java 访问SharedReference在Android中不起作用
我有两项活动。在第一个活动中,我将把一个字符串放入共享首选项中。然后我记录getString,我看到它出现了。然后,我进入第二个活动,对getString进行Toast,得到显示的默认值 第一个活动代码:Java 访问SharedReference在Android中不起作用,java,android,sharedpreferences,Java,Android,Sharedpreferences,我有两项活动。在第一个活动中,我将把一个字符串放入共享首选项中。然后我记录getString,我看到它出现了。然后,我进入第二个活动,对getString进行Toast,得到显示的默认值 第一个活动代码: SharedPreferences.Editor pref_editor = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE).edit(); SharedPreferences pref = mcontext.getSh
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();
第二个活动代码:
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”吗?您没有在编辑器上调用commit。更改是批处理的,在调用commit之前不会写入磁盘。您是否已尝试应用()?请尝试以下操作:-
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();
OP正在调用coomit-see
pref_editor.putString(“test”,“It works!”).commit()代码>日志打印出来了吗?对我有用。唯一不同的是我的Context
s是每个活动实例。commit()
的返回值是多少?使用getApplicationContext()
反复尝试,没有问题。我建议清理这个项目,它可能会有所帮助。同时从测试设备中清除应用程序的数据。卸载应用程序,然后再次运行。现在它起作用了。啊。谢谢