Open In App

Android – Login and Logout Using Shared Preferences in Kotlin

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Using Shared Preferences We can store data locally on our Android applications. 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 use Shared Preferences to store users’ credentials. Now we will move toward the implementation part. A sample video is given below to get an idea about what we are going to do in this article.

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 Kotlin 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>
    <string name="app_name">sharedPreferences</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 the 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 Kotlin. Name the activity as HomeActivity. 

Step 5: 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.example.sharedpreferences
  
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() {
  
    // creating constant keys for shared preferences.
    companion object {
        const val SHARED_PREFS = "shared_prefs"
        const val EMAIL_KEY = "email_key"
        const val PASSWORD_KEY = "password_key"
    }
  
    // variable for shared preferences.
    private lateinit var sharedpreferences: SharedPreferences
    private var email: String? = null
    private var password: String? = null
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initializing EditTexts and our Button
        val emailEdt = findViewById<EditText>(R.id.idEdtEmail)
        val passwordEdt = findViewById<EditText>(R.id.idEdtPassword)
        val loginBtn = findViewById<Button>(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)
  
        // calling on click listener for login button.
        loginBtn.setOnClickListener {
            // to check if the user fields are empty or not.
            if (TextUtils.isEmpty(emailEdt.text.toString()) && TextUtils.isEmpty(passwordEdt.text.toString())) {
                // this method will call when email and password fields are empty.
                Toast.makeText(this@MainActivity, "Please Enter Email and Password", Toast.LENGTH_SHORT).show()
            } else {
                val editor = sharedpreferences.edit()
  
                // below two lines will put values for
                // email and password in shared preferences.
                editor.putString(EMAIL_KEY, emailEdt.text.toString())
                editor.putString(PASSWORD_KEY, passwordEdt.text.toString())
  
                // to save our data with key and value.
                editor.apply()
  
                // starting new activity.
                val i = Intent(this@MainActivity, HomeActivity::class.java)
                startActivity(i)
                finish()
            }
        }
    }
  
    override fun onStart() {
        super.onStart()
        if (email != null && password != null) {
            val i = Intent(this@MainActivity, HomeActivity::class.java)
            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.

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=".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.kt file. Add the below code inside that file.

Kotlin




package com.example.sharedpreferences
  
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 HomeActivity : AppCompatActivity() {
  
    // creating constant keys for shared preferences.
    companion object {
        const val SHARED_PREFS = "shared_prefs"
        const val EMAIL_KEY = "email_key"
        const val PASSWORD_KEY = "password_key"
    }
  
    // variable for shared preferences.
    private lateinit var sharedpreferences: SharedPreferences
    private var email: String? = null
  
    override fun onCreate(savedInstanceState: Bundle?) {
        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.
        val welcomeTV = findViewById<TextView>(R.id.idTVWelcome)
        welcomeTV.text = "Welcome $email"
        val logoutBtn = findViewById<Button>(R.id.idBtnLogout)
        logoutBtn.setOnClickListener {
            // calling method to edit values in shared prefs.
            val 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.
            val i = Intent(this@HomeActivity, MainActivity::class.java)
            startActivity(i)
            finish()
        }
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads