我有两个 Activity ,即注册和登录,我在注册类中定义了共享首选项。在 Registration 页面上,如果您单击按钮,您会从 Registration Activity 转到 Login Activity。我正在存储一个 Shared Preferences 值,以便在第二次启动该应用程序时,让该应用程序立即转到 LoginActivity,而不是打开第一个 Activity,即 Registration Activity。这是我的名为 Session 的 SharedPreferences 类。
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename).commit();
editor.commit();
public Boolean contKey(String key){
if (prefs.contains(key)){
return true;
}else{
return false;
}
}
这是 RegstrationActivity 中的按钮,它在转到 LoginActivity 之前存储 SharedPreferences 值,以便在第二次启动时打开 LoginActivity 类
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session = new Session(getApplicationContext());
session.setusename("hello123");
Intent intent = new Intent(getApplication(),ActivityLogin.class);
startActivity(intent);
finish();
}
});
我在 RegistrationActivity 类的 onCreate 方法中定义了这个,以便在下次启动应用程序时切换到 ActivityLogin 屏幕
System.out.println("it got here...2");
try {
if (session.contKey("username")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
请问为什么我的共享首选项在第二次启动时没有切换到 LoginActivity。请协助
最佳答案
试试这个
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename);
editor.commit();
}
}
public String getusename() {
return prefs.getString("username","");
}
}
比使用这种方式获取值 SharedPreferences
session = new Session(getApplicationContext());
session.setusename("hello123");
String username=session.getusename();
示例代码
try {
if (!session.getusename().equals("")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
关于java - 共享首选项未检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47469551/