gpt4 book ai didi

android - onViewStateRestored 崩溃的 Android 应用程序

转载 作者:行者123 更新时间:2023-11-29 19:30:02 24 4
gpt4 key购买 nike

我是 Android 开发的初学者。我想保存用户登录数据,这样他就不必在暂停和恢复应用程序后或再次使用该应用程序时登录。在浏览了一些关于 stackoverflow 的帖子后,我意识到 onSavedInstance 是实现它的方法。

我已经在一个 loginActivity 中实现了这些方法,但是当我在模拟器上打开这个 Activity 时,应用程序给出了一个错误。错误是Unfortunately, 'Project_name' has stopped

所以,我检查了日志文件,得到了这个

java.lang.NullPointerException:尝试在空对象引用上调用虚方法“boolean android.os.Bundle.getBoolean(java.lang.String)”

在线

boolean inSession = savedInstanceState.getBoolean("loggedin");

在 onViewStateRestored 方法中。

谁能帮我找出我哪里出错了,有没有更好的方法来存储登录详细信息,这样用户就不必在每次应用程序进入暂停或停止模式时都登录?

提前感谢您的帮助。 :)

 @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
if(inSession){
savedInstanceState.putBoolean("loggedin",true);
savedInstanceState.putString("email",emailcol);
savedInstanceState.putString("password",passwordcol);
savedInstanceState.putString("type","login");
}
else{
savedInstanceState.putBoolean("loggedin",false);

}
}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);

boolean inSession = savedInstanceState.getBoolean("loggedin");
if (inSession) {
String email = savedInstanceState.getString("email");
String pass = savedInstanceState.getString("password");
String type = "login";
BackgroundWorker bw = new BackgroundWorker(this.getContext());
//(Name,password,email,contact,address,type
bw.execute(null, pass, email, null, null, type);
}

}

最佳答案

根据安卓documentation当您的 Activity 在之前被销毁后重新创建时,您可以从系统传递给您的 Activity 的 Bundle 中恢复您保存的状态。 onCreate() 和 onRestoreInstanceState() 回调方法都接收到包含实例状态信息的相同 Bundle。

因为无论系统是创建 Activity 的新实例还是重新创建以前的实例,都会调用 onCreate() 方法,因此在尝试读取状态 Bundle 之前,您必须检查状态 Bundle 是否为空。如果它为 null,则系统正在创建该 Activity 的一个新实例,而不是恢复之前被销毁的实例。

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first

// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...

您可能应该使用 Shared Preferences存储用户登录信息

关于android - onViewStateRestored 崩溃的 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com