Shared Preference or Session Management (Login-Logout)

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.

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".

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.

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:
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);

You can see your sharedpreference data in android device monitor. In Android Studio, find Android Device Monitor, as below image:

In Android Device Monitor, in left panel select emulator, and then right side navigate to the directory, data->data->your_package_name->shared_prefs
You find a file named login.xml, now pull file from device using this option at right-top side,
Now open file, you can see content of your sharedpreference data..

Comments

Popular posts from this blog

SQLiteDatabase (Without SqliteOpenHelper class)

Set current date to Button and Datepicker dialog

MVC Architecture in Android