Android Session Management with Examples

  Keywords : Android session management will help us to store the user data globally outside of the application, Android user session management using shared preferences with examples

Here we will learn session management in android using sharedpreferences with examples, how to use android shared preferences to store and retrieve session values when the user login to application and clear or delete the values in shared preferences file whenever the user clicks on logout button in android application with examples.

Android Session Management

In android, Session Management is a process which is used to maintain the required values in a session to use it in application.

 

Generally, in android we can manage the logged in user details in session either by storing it in global variables or in Shared Preferences. In case, if we store the values in global variables, those will be lost whenever the user closes the application but if we store the values in Shared Preferences, those will be persisted even if the application closed by user.

 

In android, Shared Preferences are used to save and retrieve the primitive data types (integer, float, Boolean, string, long) data in the form of key-value pair from a file within an apps file structure.

 

To know more about Shared Preferences, check this Android Shared Preferences with Examples.

 

Now we will see how to store and retrieve logged in user details from shared preferences file using SharedPreferences object and clear or delete the stored session values from Shared Preferences file whenever the user clicks on logout button in android application with examples.

Android Session Management Example

Following is the example of storing and retrieving the logged in user details from shared preferences file using SharedPreferences and clear the stored session values on logout button click.

 

Create a new android application using android studio and give names as SharedPreferencesExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
TextView
       
android:id="@+id/fstTxt"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:layout_marginTop="150dp"
       
android:text="UserName" />
    <
EditText
       
android:id="@+id/txtName"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:ems="10"/>
    <
TextView
       
android:id="@+id/secTxt"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Password"
       
android:layout_marginLeft="100dp" />
    <
EditText
        
android:id="@+id/txtPwd"
       
android:inputType="textPassword"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:ems="10" />
    <
Button
       
android:id="@+id/btnLogin"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="100dp"
       
android:text="Login" />
</
LinearLayout>

Now we will create another layout resource file details.xml in \res\layout path to get the first activity (activity_main.xml) details in second activity file for that right click on your layout folder à Go to New à select Layout Resource File and give name as details.xml.

 

Once we create a new layout resource file details.xml, open it and write the code like as shown below

details.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:id="@+id/resultView"
       
android:layout_gravity="center"
       
android:layout_marginTop="170dp"
       
android:textSize="20dp"/>
    <
Button
       
android:id="@+id/btnLogOut"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_gravity="center"
       
android:layout_marginTop="20dp"
       
android:text="Log Out" />
</
LinearLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.sharedpreferencesexample path and write the code like as shown below

MainActivity.java

package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText
uname, pwd;
    Button
loginBtn;
    SharedPreferences
pref;
    Intent
intent;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
uname = (EditText)findViewById(R.id.txtName);
       
pwd = (EditText)findViewById(R.id.txtPwd);
       
loginBtn = (Button)findViewById(R.id.btnLogin);
       
pref = getSharedPreferences("user_details",MODE_PRIVATE);
       
intent = new Intent(MainActivity.this,DetailsActivity.class);
       
if(pref.contains("username") && pref.contains("password")){
            startActivity(
intent);
        }
       
loginBtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                String username =
uname.getText().toString();
                String password =
pwd.getText().toString();
                
if(username.equals("suresh") && password.equals("dasari")){
                    SharedPreferences.Editor editor =
pref.edit();
                    editor.putString(
"username",username);
                    editor.putString(
"password",password);
                    editor.commit();
                    Toast.makeText(getApplicationContext(),
"Login Successful",Toast.LENGTH_SHORT).show();
                    startActivity(
intent);
                }
               
else
               
{
                    Toast.makeText(getApplicationContext(),
"Credentials are not valid",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

If you observe above code, we are checking whether the entered username and password details matching or not based on that we are saving the details in shared preferences file and redirecting the user to another activity.

 

Now we will create another activity file DetailsActivity.java in \java\com.tutlane.sharedpreferencesexample path to show the details from shared preference file for that right click on your application folder à Go to New à select Java Class and give name as DetailsActivity.java.

 

Once we create a new activity file DetailsActivity.java, open it and write the code like as shown below

DetailsActivity.java

package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by tutlane on 03-01-2018.
 */

public class DetailsActivity extends AppCompatActivity {
    SharedPreferences
prf;
    Intent
intent;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
details);
        TextView result = (TextView)findViewById(R.id.
resultView);
        Button btnLogOut = (Button)findViewById(R.id.
btnLogOut);
       
prf = getSharedPreferences("user_details",MODE_PRIVATE);
       
intent = new Intent(DetailsActivity.this,MainActivity.class);
        result.setText(
"Hello, "+prf.getString("username",null));
        btnLogOut.setOnClickListener(
new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                SharedPreferences.Editor editor =
prf.edit();
                editor.clear();
                editor.commit();
                startActivity(
intent);
            }
        });
    }
}

Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.tutlane.sharedpreferencesexample">
    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <
activity android:name=".DetailsActivity" android:label="Shared Preferences - Details"></activity>
    </
application>
</
manifest>

If you observe above example, we are checking whether the entered user details matching or not based on that we are saving the user details in shared preferences file and redirecting the user to another activity file (DetailsActivity.java) to show the users details and added all the activities in AndroidManifest.xml file.

Output of Android Session Management Example

When we run above example in android emulator we will get a result like as shown below

 

Android Session Management Example Result

 

If you observe above result, the entered username and password matches then we are redirecting user to another activity file to show the user details from shared preferences file. After that, if we click on Logout button, it will clear all the values in shared preferences file and it will redirect user to login page.

 

This is how we can use session management in android applications with Shared Preferences to store and retrieve session values based on our requirements.