Open In App

Android Session Management using Jetpack Compose

Last Updated : 27 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
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. We will be using shared preferences for managing the session of the user within the android application. In this article, we will be implementing session management in the android application using Jetpack Compose

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. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

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

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors
val greenColor = Color(0xFF0F9D58)


Step 3: Creating a new MainActivity2

Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Gallery > Select Empty Compose activity and name the activity a MainActivity2.kt file. 

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.example.newcanaryproject
 
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Password
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import com.example.newcanaryproject.ui.theme.*
 
class MainActivity : ComponentActivity() {
 
    // 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 variable
    // for email as e and password as p.
    var e = ""
    var p = ""
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // on below line we are initializing our shared preferences.
            sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
 
            // on below line we are creating
            // variable for email and password.
            val email = remember {
                mutableStateOf("")
            }
            val pwd = remember {
                mutableStateOf("")
            }
 
            // on below line we are initializing values for both email and password.
            email.value = sharedPreferences.getString(EMAIL_KEY, "").toString()
            pwd.value = sharedPreferences.getString(PWD_KEY, "").toString()
 
            // on below line we are setting value
            // from email and password to e and p
            e = email.value
            p = pwd.value
 
 
            NewCanaryProjectTheme {
                // on below line we are specifying background
                // color for our application
                Surface(
                    // on below line we are specifying
                    // modifier and color for our app
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
 
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
 
                        // in scaffold we are specifying top bar.
                        topBar = {
 
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying title
                                // for our top bar.
                                title = {
 
                                    // in the top bar we are specifying tile as a text
                                    Text(
 
                                        // on below line we are specifying text to display in top app bar.
                                        text = "Session Management in Android",
 
                                        // on below line we are specifying modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
 
                        // on below line we are calling session management
                        // method and passing shared preferences to it.
                        sessionManagement(sharedPreferences)
                    }
                }
            }
        }
 
    }
 
    // on below line we are calling on start method.
    override fun onStart() {
        super.onStart()
        // on below line we are creating a variable for activity.
        val activity = (this as? Activity)
 
        // on below line we are initializing our shared preferences.
        sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
 
        // on below line we are initializing our email and pwd
        // variable setting values from shared preferences.
        val email = sharedPreferences.getString(EMAIL_KEY, "").toString()
        val pwd = sharedPreferences.getString(PWD_KEY, "").toString()
 
        // on below line we are checking if email and pwd are empty or not.
        if (email != "" && pwd != "") {
            // if email and pwd are not empty we are opening
            // a new activity on below line.
            val i = Intent(this, MainActivity2::class.java)
 
            // on below line we are starting our new activity
            // and finishing our current activity.
            startActivity(i)
            activity?.finish()
        }
    }
}
 
// on below line we are creating a function for session management
@Composable
fun sessionManagement(sharedPreferences: SharedPreferences) {
 
    // on below line we are creating a variable for
    // context and activity and initializing it.
    val ctx = LocalContext.current
    val activity = (LocalContext.current as? Activity)
 
    // on below line we are creating and
    // initializing email value and pwd value
    val emailValue = remember {
        mutableStateOf(TextFieldValue())
    }
    val pwdValue = remember {
        mutableStateOf(TextFieldValue())
    }
 
    // on the below line we are creating a column.
    Column(
        // on below line we are adding a modifier to it
        // and setting max size, max height and max width
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth(),
 
        // on below line we are adding vertical
        // arrangement and horizontal alignment.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line we are creating a text
        Text(
            // on below line we are specifying text as
            // Session Management in Android.
            text = "Session Management in Android",
 
            // on below line we are specifying text color.
            color = greenColor,
 
            // on below line we are specifying font family
            fontFamily = FontFamily.Default,
 
            // on below line we are adding font weight
            // and alignment for our text
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
 
        // on below line we are creating a text field for our email.
        TextField(
            // on below line we are specifying value for our email text field.
            value = emailValue.value,
 
            // on below line we are adding on value change for text field.
            onValueChange = { emailValue.value = it },
 
            // on below line we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your email") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
 
            // on below line we are adding single line to it.
            singleLine = true,
 
            // on below line we are specifying leading icon as email
            leadingIcon = {
                Icon(imageVector = Icons.Default.Email, contentDescription = "Email")
            }
        )
 
        // on below line we are creating a text field for password.
        TextField(
            // on below line we are specifying value for our password as pwdValue.
            value = pwdValue.value,
 
            // on below line we are specifying on value change for it.
            onValueChange = { pwdValue.value = it },
 
            // on below line we are adding place holder to it as enter your password.
            placeholder = { Text(text = "Enter your password") },
 
            // on below line we are adding modifier to it and padding to it.
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style for our text and font size.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
 
            // on below line we are adding single line to it.
            singleLine = true,
 
            // on below line we are adding visual
            // transformation it obscure the password.
            visualTransformation = PasswordVisualTransformation(),
 
            // on below line we are adding leading icon to it.
            leadingIcon = {
                Icon(imageVector = Icons.Default.Password, contentDescription = "Email")
            }
        )
 
        // on the below line we are adding a button for login.
        Button(
            // on below line we are adding modifier to
            // it for adding padding and max width.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
 
            // on below line we are adding on click to this button.
            onClick = {
                // on below line we are calling save data method
                // to save data to shared preferences.
                saveData(emailValue.value.text, pwdValue.value.text, sharedPreferences, ctx)
 
                // on the below line we are calling finish to close the current activity.
                activity?.finish()
            },
            // on below line we are adding color to our button.
            colors = ButtonDefaults.buttonColors(
                backgroundColor = greenColor,
            )
        )
        // on the below line we are adding text as login.
        {
            Text(text = "Login")
        }
    }
}
 
// on below line we are creating a function as save data
// to save data in our shared preferences.
fun saveData(email: String, pwd: String, sharedPreferences: SharedPreferences, context: Context) {
    // on below line we are creating an editor and initializing
    // it with shared preferences.
    val editor: SharedPreferences.Editor = sharedPreferences.edit()
 
    // on below line we are setting email and pwd value with key.
    editor.putString("email", email)
    editor.putString("pwd", pwd)
 
    // on the below line we are applying
    // changes to our shared prefs.
    editor.apply()
 
    // on below line we are opening a new intent.
    val i = Intent(context, MainActivity2::class.java)
    context.startActivity(i)
}


Step 5: Working with the MainActivity2.kt file

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

Kotlin




package com.example.newcanaryproject
 
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
 
class MainActivity2 : ComponentActivity() {
 
    // on below line we are creating a variable for our 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"
 
    // on below line we are creating a variable for email
    var email = ""
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        // on below line we are initializing our shared preferences.
        sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
 
        // on below line we are initializing our email from shared preferences.
        email = sharedPreferences.getString(EMAIL_KEY, "").toString()
 
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying
                // background color for our application
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
                        // in scaffold we are specifying top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
 
                                        // on below line we are specifying text to display in top app bar.
                                        text = "Session Management in Android",
 
                                        // on below line we are specifying modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
 
                        // on below line we are calling get data and passing email and shared preferences to it.
                        getData(email, sharedPreferences)
                    }
                }
            }
        }
    }
}
 
// on below line we are creating a get data method.
@Composable
fun getData(email: String, sharedPreferences: SharedPreferences) {
    // on below line we are creating and initializing
    // our context variable and activity.
    val ctx = LocalContext.current
    val activity = (LocalContext.current as? Activity)
 
    // on below line we are creating a column
    Column(
        // inside the column we are adding modifier
        // and specifying max height, max width and max size.
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .fillMaxSize(),
 
        // on below line we are specifying
        // vertical arrangement for our column.
        verticalArrangement = Arrangement.Center,
 
        // on below line we are specifying horizontal alignment for our column.
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line we are creating a text for displaying user name
        Text(
            // on below line we are specifying text in our text
            text = "Welcome \n" + email,
 
            // on below line we are specifying font weight for our text
            fontWeight = FontWeight.Bold,
 
            // on below line we are adding green color to it.
            color = greenColor,
 
            // on below line we are specifying font size to it.
            fontSize = 20.sp,
 
            // on below line we are adding alignment for our text
            textAlign = TextAlign.Center
        )
 
        // on below line we are adding spacer between text and button.
        Spacer(modifier = Modifier.height(50.dp))
 
        // on below line we are adding button.
        Button(
 
            // on below line we are adding modifier to
            // fill max width and adding padding to it.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
 
            // on below line we are adding on click for our button.
            onClick = {
 
                // on below line we are creating a variable for our editor.
                val editor: SharedPreferences.Editor = sharedPreferences.edit()
 
                // on below line we are passing email and pwd with empty values.
                editor.putString("email", "")
                editor.putString("pwd", "")
 
                // on below line we are applying changes which are updated.
                editor.apply()
 
                // on below line we are opening our main activity.
                val i = Intent(ctx, MainActivity::class.java)
                ctx.startActivity(i)
                activity?.finish()
            },
            // on below line we are adding color for out button
            colors = ButtonDefaults.buttonColors(
                backgroundColor = greenColor,
            )
        ) {
            // on below line we are adding text for our button.
            Text(text = "Log Out")
        }
 
    }
}


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