Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Session Management in Android with Example
Next article icon

Session Management in Android with Example

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 


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:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <!-- Toolbar for ActionBar -->     <androidx.appcompat.widget.Toolbar         android:id="@+id/toolbar"         app:title="@string/app_name"         app:titleTextColor="@color/white"         android:layout_width="match_parent"         android:layout_height="?attr/actionBarSize"         android:background="?attr/colorPrimary" />      <!-- 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_below="@id/toolbar"         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 get 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);          // check if the fields are not null then one current user is loggedIn          if (email != null && password != null) {             Intent i = new Intent(MainActivity.this, HomeActivity.class);             startActivity(i);             finish();         }          // 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();                 }             }         });     } } 


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


Next Article
Session Management in Android with Example

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Android-Misc
Practice Tags :
  • Java

Similar Reads

    Android Session Management with Kotlin
    Session Management is seen in most of the android applications in which we can get to know the login and sign-up page. This is used to store the session of the user when he is logged into the application. When the user login inside the application for the first time. The user credentials such as ema
    7 min read
    Intent Service in Android with Example
    An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as "Intents") on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it. An IntentService in Java and Kotlin: Kotlin class MyIntentServi
    5 min read
    Android Session Management using Jetpack Compose
    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 u
    13 min read
    Services in Android with Example
    Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at t
    10 min read
    Android ListView in Java with Example
    A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences