You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SharedPreferences实现登录会话异常:登录后跳转回登录页

Fix: Session Not Persisting, Redirecting Back to LoginActivity

Hey there, I can spot the exact issue causing your login session to not stick—you're using the wrong key when saving the login state in your SessionManager class!

The Root Problem

In your createSession method, you're storing the login status using the PREF_NAME constant (which is "LOGIN"):

editor.putBoolean(PREF_NAME, true);

But in your isLoggedIn method, you're checking for the LOGIN constant (which is "IS_LOGIN"):

return sharedPreferences.getBoolean(LOGIN, false);

These are two completely different keys, so the isLoggedIn method always returns false—that's why your MainActivity immediately redirects back to LoginActivity right after login.

The Fix

Update the createSession method to use the LOGIN constant instead of PREF_NAME when setting the login status:

public void createSession(String name, String email, String type){
    // Replace PREF_NAME with LOGIN here
    editor.putBoolean(LOGIN, true);
    editor.putString(NAME, name);
    editor.putString(EMAIL, email);
    editor.putString(TYPE, type);
    editor.apply();
}

Bonus: A Minor Safety Improvement

In your checkLoggin (quick typo note: should be checkLogin) method, you're casting context directly to MainActivity:

((MainActivity) context).finish();

If you ever use this method from a different activity later, this will cause a crash. To make it more robust, add a check first:

public void checkLoggin(){
    if (!this.isLoggedIn()){
        Intent i = new Intent(context, LoginActivity.class);
        context.startActivity(i);
        // Check if context is an Activity before casting
        if (context instanceof Activity) {
            ((Activity) context).finish();
        }
    }
}

That should fix the immediate redirect issue—your session will now persist correctly, and isLoggedIn will return true after you call createSession.

内容的提问来源于stack exchange,提问作者courage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:00:52