Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Session Management in Android with Example

  • Last Updated : 23 Feb, 2021

Session Management is one of the most important features that are to be used in the Android App when you are integrating the login feature in Android. In your android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home screen, rather than opening a login screen. So in this article, we will implement Session Management functionality in our Android app. For implementing this functionality we are creating a simple login form and a home screen. In our login form, the user has to enter his credentials and login into the app. After login, the user’s credentials will be saved inside the app, and whenever he reopens the app the user will be redirected to the home screen. For session management inside our app, we will be using Shared Preferences to store users’ credentials. Now we will move towards the implementation part.

Example

We will be creating a simple Login app as mentioned above for storing user session. A sample GIF is given below in which we will get to see what we will be building in our app. Note that we will be implementing this project using Java language. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Session Management in Android sample GIF

Step by Step Implementation

Step 1: Create a New Project



To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. 

Step 2: Add the below strings in your strings.xml file

Navigate to the app > res > values > strings.xml and add the below strings to it. 

XML




<resources>
    <!--app name-->
    <string name="app_name">Session Management</string>
    <!--string for login button-->
    <string name="login">Login</string>
    <!--string for edittext hint in password-->
    <string name="enter_password">Enter password</string>
    <!--string for edittext hint in email-->
    <string name="enter_youe_email">Enter your Email</string>
    <!--string for logout button-->
    <string name="logout">Logout</string>
</resources>

Step 3: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--EditText for getting user email address-->
    <!--input type is set to email-->
    <EditText
        android:id="@+id/idEdtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="10dp"
        android:hint="@string/enter_youe_email"
        android:importantForAutofill="no"
        android:inputType="textEmailAddress" />
  
  
    <!--EditText for getting user password-->
    <!--input type is set to password-->
    <EditText
        android:id="@+id/idEdtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmail"
        android:layout_marginStart="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="10dp"
        android:hint="@string/enter_password"
        android:importantForAutofill="no"
        android:inputType="textPassword" />
  
    <!--button to continue to login-->
    <Button
        android:id="@+id/idBtnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtPassword"
        android:layout_marginStart="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="10dp"
        android:text="@string/login" />
  
</RelativeLayout>

Step 4: Create a new Activity for Home Screen 



Navigate to the app > java > your app’s package name > Right-Click on your package name and New > Activity > Empty Activity and make sure to keep your language as Java. Name the activity as HomeActivity. 

Step 5: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // creating constant keys for shared preferences.
    public static final String SHARED_PREFS = "shared_prefs";
      
    // key for storing email.
    public static final String EMAIL_KEY = "email_key";
      
    // key for storing password.
    public static final String PASSWORD_KEY = "password_key";
      
    // variable for shared preferences.
    SharedPreferences sharedpreferences;
    String email, password;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Initializing EditTexts and our Button
        EditText emailEdt = findViewById(R.id.idEdtEmail);
        EditText passwordEdt = findViewById(R.id.idEdtPassword);
        Button loginBtn = findViewById(R.id.idBtnLogin);
  
        // getting the data which is stored in shared preferences.
        sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
          
        // in shared prefs inside het string method
        // we are passing key value as EMAIL_KEY and 
        // default value is
        // set to null if not present.
        email = sharedpreferences.getString(EMAIL_KEY, null);
        password = sharedpreferences.getString(PASSWORD_KEY, null);
  
        // calling on click listener for login button.
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // to check if the user fields are empty or not.
                if (TextUtils.isEmpty(emailEdt.getText().toString()) && TextUtils.isEmpty(passwordEdt.getText().toString())) {
                    // this method will call when email and password fields are empty.
                    Toast.makeText(MainActivity.this, "Please Enter Email and Password", Toast.LENGTH_SHORT).show();
                } else {
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                      
                    // below two lines will put values for 
                    // email and password in shared preferences.
                    editor.putString(EMAIL_KEY, emailEdt.getText().toString());
                    editor.putString(PASSWORD_KEY, passwordEdt.getText().toString());
                      
                    // to save our data with key and value.
                    editor.apply();
                      
                    // starting new activity.
                    Intent i = new Intent(MainActivity.this, HomeActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        });
    }
  
    @Override
    protected void onStart() {
        super.onStart();
        if (email != null && password != null) {
            Intent i = new Intent(MainActivity.this, HomeActivity.class);
            startActivity(i);
        }
    }
}

Step 6: Now we will work on our Home Screen

Inside our home screen, we will be displaying users’ email address and a logout button so that users can Logout of the app. For Home Screen, we have created an activity named as HomeActivity. Navigate to the app > res > layout > activity_home.xml and open it and add the below code to it. 

Java




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity">
  
    <!--Textview for displaying
        user's email address-->
    <TextView
        android:id="@+id/idTVWelcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="5dp"
        android:textAlignment="center"
        android:textSize="20sp" />
  
    <!--button for logging out of the app-->
    <Button
        android:id="@+id/idBtnLogout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVWelcome"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="20dp"
        android:text="@string/logout" />
  
</RelativeLayout>

Now we will move towards the java file of our HomeActivity. Navigate to the app > java > your app’s package name and open the HomeActivity.java file. Add below code inside that file. 

Java




import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
  
public class HomeActivity extends AppCompatActivity {
  
    // creating constant keys for shared preferences.
    public static final String SHARED_PREFS = "shared_prefs";
      
    // key for storing email.
    public static final String EMAIL_KEY = "email_key";
      
    // key for storing password.
    public static final String PASSWORD_KEY = "password_key";
      
    // variable for shared preferences.
    SharedPreferences sharedpreferences;
    String email;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
          
        // initializing our shared preferences.
        sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
          
        // getting data from shared prefs and 
        // storing it in our string variable.
        email = sharedpreferences.getString(EMAIL_KEY, null);
          
        // initializing our textview and button.
        TextView welcomeTV = findViewById(R.id.idTVWelcome);
        welcomeTV.setText("Welcome \n" + email);
        Button logoutBtn = findViewById(R.id.idBtnLogout);
        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  
                // calling method to edit values in shared prefs.
                SharedPreferences.Editor editor = sharedpreferences.edit();
                  
                // below line will clear 
                // the data in shared prefs.
                editor.clear();
                  
                // below line will apply empty
                // data to shared prefs.
                editor.apply();
                  
                // starting mainactivity after
                // clearing values in shared preferences.
                Intent i = new Intent(HomeActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        });
    }
}

Output:

Check out the GitHub link: https://github.com/ChaitanyaMunje/SessionManagementAndroid




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!