Android Session Management Using SharedPreferences

Here you will get an example of android session management using SharedPreferences.

If you don’t know about SharedPreferences then read my previous tutorial: Android SharedPreferences Example

In this tutorial you will learn how to manage login session of user. The whole process works like this:

  • When user enters correct username and password then the login details are stored in SharedPreferences and user is redirected to home or welcome screen. After opening home screen I have killed or finished login screen so that user can’t go back.
  • Now even if user closes the app and open it again then he did not require to enter the login details because the details are already stored in SharedPreferences. He will be directly redirected to home screen.
  • When user click on logout button, the data stored in SharedPreferences is deleted and login session is destroyed. The user is redirected to login screen and home screen is killed so that he can’t go back.

 

In this way user login session is managed. Session management concept is very important and frequently used while developing any android app.

Below I have shared an example that will help you to implement it in your app.

 

Android Session Management Using SharedPreferences

Create a new project with package name com.sessionmanagement.

Now create two blank activities with name MainActivity and Home. By default you may get MainActivity, in that case you have to create only Home activity.

Now add following code in respective files.

 

Note: Here I have used programmer as username and password. You can change the login details according to you or you can get the details from server or database and then compare with it.

 

MainActivity.java

package com.sessionmanagement;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


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 directly redirect to Home activity
        if(sp.contains("username") && sp.contains("password")){
            startActivity(new Intent(MainActivity.this,Home.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("programmer") && password.getText().toString().equals("programmer")){
            SharedPreferences.Editor e=sp.edit();
            e.putString("username","programmer");
            e.putString("password","programmer");
            e.commit();

            Toast.makeText(MainActivity.this,"Login Successful",Toast.LENGTH_LONG).show();

            startActivity(new Intent(MainActivity.this,Home.class));
            finish();
        }
        else{
            Toast.makeText(MainActivity.this,"Incorrect Login Details",Toast.LENGTH_LONG).show();
        }
    }
}

 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp" tools:context=".MainActivity"
    android:orientation="vertical">

    <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="Enter Username"
        android:id="@+id/username"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Enter 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>

 

Home.java

package com.sessionmanagement;

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 Home 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(Home.this,MainActivity.class));
                finish();   //finish current activity
            }
        });
    }
}

 

activity_home.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp" tools:context=".MainActivity"
    android:orientation="vertical">

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

 

Finally run and test your app.

 

Output

Android Session Management Using SharedPreferences

Android Session Management Using SharedPreferences

Comment below if you have any queries related to above android session management tutorial.

Happy Coding!! 🙂 🙂

11 thoughts on “Android Session Management Using SharedPreferences”

  1. same code i wrote but while im going to run, that time app crashed and asking for wait or close, anyone can tell why it is so…??
    thanks in advanse

  2. Hi Neeraj, I have some error like this, java.lang.NullPointerException: Attempt to invoke virtual method ‘android.text.Editable android.widget.EditText.getText()’ on a null object reference. can you solve this probel, please ? I’m newbie.

  3. i couldn’t find a line which shows the connection to any database. or this tutorial just give an idea to implement without the database?

    1. Yes this tutorial is written to explain the implementation of session management without database. You can implement it along with database.

Leave a Comment

Your email address will not be published. Required fields are marked *