Open In App

Android Session Management with Kotlin

Last Updated : 22 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 email and password are stored within the shared preferences. When the user opens the application again the user will be redirected to the app’s home screen rather than login again and again. Shared Preferences is a class within Android which we can use to store the user credentials and maintain the session of the user. In this article, we will be creating a simple application where we will take a look at Session Management.   

Note: If you want to implement Calendar View in Android applications using Java. Check out the following article: Session Management in Android with Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

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

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

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"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a new text view-->
    <TextView
        android:id="@+id/idTVHead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:gravity="center"
        android:padding="8dp"
        android:text="Session Management in Android Example"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating edit text for our email-->
    <EditText
        android:id="@+id/idEdtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHead"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:layout_marginEnd="20dp"
        android:hint="Enter your email" />
 
    <!--on below line we are creating edit text for password-->
    <EditText
        android:id="@+id/idEdtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmail"
        android:layout_marginStart="20dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="20dp"
        android:hint="Enter your password"
        android:inputType="textPassword" />
 
    <!--on below line we are creating a button for login-->
    <Button
        android:id="@+id/idBtnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtPassword"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:layout_marginEnd="20dp"
        android:padding="4dp"
        android:text="Login"
        android:textAllCaps="false" />
 
</RelativeLayout>


Step 3: Create a new Activity as MainActivity2

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

Step 4: Working with the MainActivity.kt file

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

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating
    // variable for email and password edit text.
    lateinit var emailEdt: EditText
    lateinit var pwdEdt: EditText
 
    // on below line we are creating
    // a variable for our button.
    lateinit var loginBtn: Button
 
    // on below line we are creating
    // a variable for shared preferences.
    lateinit var sharedPreferences: SharedPreferences
 
    // on below line we are creating a variable
    // for prefs key and email key and pwd key.
    var PREFS_KEY = "prefs"
    var EMAIL_KEY = "email"
    var PWD_KEY = "pwd"
 
    // on below line we are creating a
    // variable for email and password.
    var email = ""
    var pwd = ""
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing
        // our email and pwd edit text
        emailEdt = findViewById(R.id.idEdtEmail)
        pwdEdt = findViewById(R.id.idEdtPassword)
 
        // on below line we are initializing
        // our login button with id.
        loginBtn = findViewById(R.id.idBtnLogin)
 
        // on below line we are initializing our shared preferences.
        sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
 
        // on below line we are getting data from
        // our shared prefs and setting it to email.
        email = sharedPreferences.getString(EMAIL_KEY, "").toString()
 
        // on below line we are getting data from
        // shared prefs and setting it to pwd.
        pwd = sharedPreferences.getString(PWD_KEY, "").toString()
 
        // on below line we are adding on click listener for our login button.
        loginBtn.setOnClickListener {
            // on below line we are checking if email and pwd txt is empty or not.
            if (TextUtils.isEmpty(emailEdt.text.toString()) && TextUtils.isEmpty(pwdEdt.text.toString())) {
 
                // if email and pwd edit text is empty we are displaying a toast message
                Toast.makeText(this, "Please Enter Email and Password", Toast.LENGTH_SHORT).show();
 
            } else {
                // on below line we are creating variable for editor
                // of shared prefs and initializing it.
                val editor: SharedPreferences.Editor = sharedPreferences.edit()
 
                // on below line we are adding our email and
                // pwd to shared prefs to save them.
                editor.putString(EMAIL_KEY, emailEdt.text.toString())
                editor.putString(PWD_KEY, pwdEdt.text.toString())
 
                // on below line we are applying
                // changes to our shared prefs.
                editor.apply()
 
                // on below line we are opening our intent as main activity 2
                val i = Intent(this@MainActivity, MainActivity2::class.java)
 
                // on below line we are
                // starting our activity.
                startActivity(i)
 
                // on below line we are calling
                // finish to close our activity.
                finish()
            }
        }
    }
 
    // on below line we are calling on start method.
    override fun onStart() {
        super.onStart()
        // in this method we are checking if email and pwd are not empty.
        if (!email.equals("") && !pwd.equals("")) {
            // if email and pwd is not empty we
            // are opening our main 2 activity on below line.
            val i = Intent(this@MainActivity, MainActivity2::class.java)
 
            // on below line we are calling start
            // activity method to start our activity.
            startActivity(i)
 
            // on below line we are calling
            // finish to finish our main activity.
            finish()
        }
    }
}


Step 5: Working with the activity_main2.xml file

Navigate to app > res > layout > activity_main2.xml and add the code below. Comments are added in the code to get to know in detail. 

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=".MainActivity2">
 
    <!--on below line we are creating a
         simple text view for heading-->
    <TextView
        android:id="@+id/idTVHead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:gravity="center"
        android:padding="8dp"
        android:text="Session Management in Android Example"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating a
        text view for displaying user name-->
    <TextView
        android:id="@+id/idTVUserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHead"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="User Name"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating
         a button for logout-->
    <Button
        android:id="@+id/idBtnLogOut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVUserName"
        android:layout_marginStart="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="20dp"
        android:padding="5dp"
        android:text="Logout"
        android:textAllCaps="false" />
 
</RelativeLayout>


Step 6: Working with the MainActivity2.kt file

Navigate to app > java > your app’s package name > MainActivity2.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity2 : AppCompatActivity() {
 
    // on below line we are creating a variable
    // for text view, string for email
    // and prefs key and an email string.
    lateinit var userTV: TextView
    lateinit var logoutBtn: Button
    var PREFS_KEY = "prefs"
    var EMAIL_KEY = "email"
    var email = ""
 
    // on below line we are creating a variable for shared preferences.
    lateinit var sharedPreferences: SharedPreferences
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
         
        // on below line we are initializing
        // our user text view and logout button.
        userTV = findViewById(R.id.idTVUserName)
        logoutBtn = findViewById(R.id.idBtnLogOut)
 
        // on below line we are initializing our shared preferences variable.
        sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
 
        // on below line we are getting the data from
        // email and setting it in email variable.
        email = sharedPreferences.getString(EMAIL_KEY, null)!!
 
        // on below line we are setting a text to user text view.
        userTV.setText("Welcome \n$email")
 
        // on below line we are adding
        // on click listener for our logout button.
        logoutBtn.setOnClickListener {
 
            // on below line we are creating a variable for
            // editor of shared preferences and initializing it.
            val editor: SharedPreferences.Editor = sharedPreferences.edit()
 
            // on below line we are clearing our editor.
            editor.clear()
 
            // on below line we are applying changes which are cleared.
            editor.apply()
 
            // on below line we are opening our mainactivity by calling intent
            val i = Intent(this@MainActivity2, MainActivity::class.java)
 
            // on below line we are simply starting
            // our activity to start main activity
            startActivity(i)
 
            // on below line we are calling
            // finish to close our main activity 2.
            finish()
        }
    }
}


Now run your application to see the output of it. 

Output: 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads