Android provides many ways to store data in application. One of those ways is to use of Shared Preference.
Shared Preference allows you to save and retrieve data in the form of key-value pair. For getting shared preference data of your app, you have to call a method getSharedPreference(), that will return SharedPreference instance that contains key-value pairs of preference.
Shared Preference allows you to save and retrieve data in the form of key-value pair. For getting shared preference data of your app, you have to call a method getSharedPreference(), that will return SharedPreference instance that contains key-value pairs of preference.
SharedPreferences preferences = getSharedPreferences(“login”, Context.MODE_PRIVATE);
Remember this name “login” remains same for fetching all data related to login task and also its key:
Suppose, we put “isUserLogin” boolean true after login success, then first time app launch, in Launcher Screen we have to check same key “isUserLogin”.
Suppose, we put “isUserLogin” boolean true after login success, then first time app launch, in Launcher Screen we have to check same key “isUserLogin”.
if (preferences.contains(“isUserLogin”)) {
Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
}
It means, if shared preference data contains “isUserLogin” key, then it will redirect to Home otherwise to Login.
Now code in Login Screen when successful login to be done.
Now code in Login Screen when successful login to be done.
SharedPreferences preferences = getSharedPreferences(“login”, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(“isUserLogin”, true);
editor.commit();
SharedPreferences.Editor is used to modifying values in SharedPreference object. Once all changes you make in an editor are done, then commit to Editor.
Now on logout task, just remove that key from SharedPreference data and revert to LoginActivity like:
Now on logout task, just remove that key from SharedPreference data and revert to LoginActivity like:
SharedPreferences preferences = getSharedPreferences(“login”, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.remove(“isUserLogin”);
editor.commit();
finish();
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
Comments
Post a Comment