使用SharedPreferences实现登录会话异常:登录后跳转回登录页
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

