gpt4 book ai didi

java - SharedPreferences 注销不起作用

转载 作者:行者123 更新时间:2023-12-02 12:57:43 27 4
gpt4 key购买 nike

我有 2 个 Activity ,身份验证主页

在身份验证中,它检查用户是否已登录,如果用户已登录,则将其重定向到Mainpage.class。这就是身份验证检查用户是否登录并重定向的方式。

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
}

在主页中,我有一个注销按钮和 onClick 事件,它使用我创建的 logOut 函数。这就是注销按钮的工作原理:

void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
finish();

Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
}

这里的问题是,当我单击注销按钮时,我只是不断重定向到主页。

最佳答案

问题是您在启动 Intent 之前完成了 Activity 。这就是为什么当调用logout()时它显示MainPage。相反,您调用 Intent 后必须完成 Activity 。

因此替换您的代码如下

void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);

finish(); /****<------Moved to here---****/
}

更新

由于您在按钮的 xml 中添加 onClick 属性,因此出现错误

java.lang.IllegalStateException: Could not find method logOut(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'logoutButton'

按如下方式替换您的函数

void logOut(View v){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);

finish(); /****<------Moved to here---****/
}

但是,我认为这样解决并不是一个好主意。您应该在适配器或 fragment 中实现 onClickListener。

关于java - SharedPreferences 注销不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44373336/

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