I\'m trying to create an app which uses username and password to login, then stay logged in as long as user didn\'t logout -or didn\'t delete app data of course-, and as far
What you have done is the right, the only thing is you have not committed your preference values.
So your function will look like this
public void doLogin(String username, String password) {
Intent loginIntent = new Intent(LoginActivity.this, HomeActivity.class);
SharedPreferences.Editor editor = perf.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply(); //This line will make necessary changes in SharedPreferences file
startActivity(loginIntent);
finish();
}
add the same line on button_logout
click
Moreover, I will recommend you to create a utility class for SharedPreference operations.
create an AppPreference class :-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isUserLoggedOut(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("id_logged_in", true);
}
public static void setUserLoggedOut(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("id_logged_in", value);
mPrefsEditor.commit();
}
public static String getUserName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getString("name", "");
}
public static void setUserName(Context ctx, String value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putString("name", value);
mPrefsEditor.commit();
}
}
and now set details in AppPreference Class:-
AppPreference.setUserLoggedOut(this, false);
AppPreference.setUserName(this, "pass username here");
and get username like this:-
AppPreference.getUserName(this);
or check user is logged or not on splash screen :-
if (isUserLoggedOut(StartActivity.this)) {
//user not logged in
} else {
//User is logged in
}
You have to commit or apply changes made in editor. So after
editor.putString("username", username);
editor.putString("password", password);
editor.apply(); // or editor.commit()