Just reset your SharedPreferences
KEY logged_in
value to false
using blockEdit.putBoolean("logged_in", false)
and commit
.
Try this:
void logOut(View view) {
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
// Set logged_in value to false
blockEdit.putBoolean("logged_in", false);
blockEdit.commit();
// Start Authentication
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
// Finish MainPage
finish();
}
#. Best practice is to create a common class
for session
management and use this from anywhere in your application as per your needs.
Crate a SessionManager
class like below:
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
Context context;
// Shared Preferences
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MY_APP";
private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";
private static final String KEY_USER_ID = "USER_ID";
private static final String KEY_USER_EMAIL = "USER_EMAIL";
private static final String KEY_USER_USERNAME = "USER_USERNAME";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn() {
return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void setUserId(int id) {
editor.putInt(KEY_USER_ID, id);
editor.commit();
}
public int getUserId() {
return sharedPreferences.getInt(KEY_USER_ID, 0);
}
public void setUsername(String username) {
editor.putString(KEY_USER_USERNAME, username);
editor.commit();
}
public String getUsername() {
return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
}
public void setEmail(String email) {
editor.putString(KEY_USER_EMAIL, email);
editor.commit();
}
public String getEmail() {
return sharedPreferences.getString(KEY_USER_EMAIL, "default@gmail.com");
}
}
USE:
LOGIN:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);
// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
LOGOUT:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);
// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
Hope this will help~