【发布时间】:2014-04-16 19:31:27
【问题描述】:
我正在尝试使用 SharedPreferences,但一直遇到以下问题。
在我创建文件并向其中添加信息的类中,我执行以下操作:
private SharedPreferences prefs = null;
private SharedPreferences.Editor editor = null;
public void setStuff (String info, boolean save, Context appCT) {
if (prefs == null && editor == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
editor = prefs.edit();
}
editor.putString("Custom", info);
editor.commit();
}
据我所知,它运行良好。但是,当我尝试从另一个类访问我存储在“首选项”中的信息时:
private static SharedPreferences prefs = null;
private static String custom = null;
public static void getStuff(Context appCT) {
if (prefs == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
custom = prefs.getString("Custom", null);
}
}
custom 的值始终为 null,就好像我从未存储过 String。谁能告诉我这是为什么?
我已经找到了答案;我正在使用 getSharedPreferences 的上下文,我遵循了我找到的所有说明和教程,但结果没有变化。
注意:这些类不在同一个应用程序中。这是一个问题吗?我不能访问其他应用程序的首选项吗?
谢谢。
【问题讨论】:
-
保存时确保“信息”不为空。确保它们在同一进程中。