我创建了一个使用Android SharedPreferences
保存一些用户名和密码的类,似乎设置用户名和密码的方法都可以。
但是每当我尝试从另一个活动中获取这些内容时,或者只是尝试打印出我接收者的值(如果试图打印该值)或null(如果试图进行i活动)。
这是我的代码:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
以下是我试图获得它的方式:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}
答案 0 :(得分:2)
完全是因为您使用Activity
作为上下文(使用getActivity()
方法的结果作为上下文)。由于您有不同的活动,因此您获得了不同的上下文,因此您将访问不同的共享首选项文件(XML)。换句话说,您正在写入活动A中的文件A
,然后使用文件B
作为源来读取活动B.这显然不会起作用。要使这一切按预期工作,您应始终对要在多个活动中访问的数据使用相同的上下文,在这种情况下,我建议使用应用程序上下文。从技术上讲,不是调用getActivity()
来获取片段中的上下文,而是调用getActivity().getApplicationContext()
来获取应用程序上下文,这样您就可以访问相同的共享首选项存储文件,无论哪个活动或片段在做什么写或读。
除此之外,没有必要致电apply()
和commit()
,因为这两者有点相同并且也是如此。请查看文档以获取更多信息。
答案 1 :(得分:1)
尝试更换:
Editor editor = preferences.edit();
与
SharedPreferences.Editor editor = preferences.edit();
然后将editor.apply();
替换为editor.commit();
。
答案 2 :(得分:0)
而不是:
editor.apply();
这样做:
editor.commit();
此外,您需要使用以下方法提交您的编辑:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");