Android – User session management with SharedPreferences
Session management is a basic and frequently taken step when developing Android applications. There are two possible ways to manage login sessions of your users : storing them in global variables, or, storing them in SharedPreferences. The problem with storing data in global variable is that it will be lost once user closes the application, but, using SharedPreferences, data persists even if the application gets closed.
If you are not familiar with SharedPreferences, you can check my previous tutorial : Introduction to SharedPreferences. If you already are, let’s get started !
Through this tutorial we will create an application, where, when user enters login and password, his data is stored in SharedPreferences and he gets redirected to home screen. If user clicks on logout button, data is deleted and login session is destroyed (then user is redirected to login screen and home screen is killed so that he can not go back) . If user closes his app, without logging out, his data is stored in SharedPreferences and he does not need to enter it again .
Create your views
Create a project with package named usersessionsample.
Add a blank activity to the already existing MainActivity. Name it HomeActivity.
Add the following code in activity_main.xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.androidprojects.esprit.usersessionsample.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Login" android:textSize="40dp"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:hint="username" android:id="@+id/username"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:hint="password" android:id="@+id/password"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:textSize="20dp" android:layout_marginTop="10dp" android:id="@+id/button"/> </LinearLayout>
And in activity_home.xml add the following :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_home" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.androidprojects.esprit.usersessionsample.HomeActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Home" android:textSize="40dp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="-- Welcome --" android:textSize="30dp" android:layout_marginTop="10dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:text="Logout" android:layout_marginTop="20dp" android:id="@+id/logout"/> </LinearLayout>
Manage user login
Now in ActivityMain.java you will redirect user to the home page once he clicks on login button, or you will directly redirect him to home page (once he closes app and gets back).
Notice that we are using amal and amalPsw as username and password here. You can change according to your needs. (get data from server or database and compare to them ect..)
package com.androidprojects.esprit.usersessionsample; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.*; public class MainActivity extends Activity { EditText username,password; Button button; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username=(EditText)findViewById(R.id.username); password=(EditText)findViewById(R.id.password); button=(Button)findViewById(R.id.button); sp=getSharedPreferences("login",MODE_PRIVATE); //if SharedPreferences contains username and password then redirect to Home activity if(sp.contains("username") && sp.contains("password")){ startActivity(new Intent(MainActivity.this,HomeActivity.class)); finish(); //finish current activity } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginCheck(); } }); } void loginCheck(){ //check username and password are correct and then add them to SharedPreferences if(username.getText().toString().equals("amal") && password.getText().toString().equals("amalPsw")){ SharedPreferences.Editor e=sp.edit(); e.putString("username","amal"); e.putString("password","amalPsw"); e.commit(); Toast.makeText(MainActivity.this,"Login Successful",Toast.LENGTH_LONG).show(); startActivity(new Intent(MainActivity.this,HomeActivity.class)); finish(); } else{ Toast.makeText(MainActivity.this,"Incorrect Login Details",Toast.LENGTH_LONG).show(); } } }
In HomeActivity.java we will manage user’s logout. Once he clicks on logout button, user gets redirected to home page and data is cleared from shared preferences :
package com.androidprojects.esprit.usersessionsample; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; public class HomeActivity extends Activity { Button logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); logout=(Button)findViewById(R.id.logout); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE); SharedPreferences.Editor e=sp.edit(); e.clear(); e.commit(); startActivity(new Intent(HomeActivity.this,MainActivity.class)); finish(); //finish current activity } }); } }
You can now run and test your application, you will get the following :
Output
You can download the source code from here.
Comment below if you have any questions .
Great, like it!
Maybe you will create “Logging with fingerprint example” in your free time.
App has to check, if login and pass have been written once already, and if they have been, and app has “check fingerprint” boolean = true in preferences, it offers to place you finger on the sensor every time you launch the app. But you still can just write login and pass instead.