Android Session Management Tutorial

Advertisements


Session help you when want to store user data outside your application, so that when the next time user use your application, you can easily get back his details and perform accordingly.

This can be done in many ways. But the most easiest and nicest way of doing this is through Shared Preferences.

Shared Preferences

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);	

You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object. Its syntax is:

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data inside shared preferences. They are listed as follows:

Sr. NOMode and description
1apply()
It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling
2clear()
It will remove all values from the editor
3remove(String key)
It will remove the value whose key has been passed as a parameter
4putLong(String key, long value)
It will save a long value in a preference editor
5putInt(String key, int value)
It will save a integer value in a preference editor
6putFloat(String key, float value)
It will save a float value in a preference editor

Session Management through Shared Preferences

In order to perform session management from shared preferences , we need to check the values or data stored in shared preferences in the onResume method. If we donot have the data, we will start the application from the beginning as it is newly installed. But if we got the data, we will start from the where the user left it. It is demonstrated in the example below:

Example

The below example demonstrates the use of Session Management. It crates a basic application that allows you to login for the first time. And then when you exit the application without logging out, you will be brought back to the same place if you start the application again. But if you logout from the application, you will be brought back to the main login screen.

To experiment with this example , you need to run this on an actual device or in an emulator .

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as SessionManagement under a package com.example.sessionmanagement. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add progress code to add session code.
3Create New Activity and it name as Welcome.java.Edit this file to add progress code to add session code.
4Modify res/layout/activity_main.xml file to add respective XML code.
5Modify res/layout/activity_welcome.xml file to add respective XML code.
6Modify res/values/string.xml file to add a message as a string constant.
7Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/com.example.sessionmanagement/MainActivity.java.

package com.example.sessionmanagement;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

   private EditText username,password;
   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String name = "nameKey"; 
   public static final String pass = "passwordKey"; 
   SharedPreferences sharedpreferences;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      username = (EditText)findViewById(R.id.editText1);
      password = (EditText)findViewById(R.id.editText2);
   }
   @Override
   protected void onResume() {
      sharedpreferences=getSharedPreferences(MyPREFERENCES, 
      Context.MODE_PRIVATE);
      if (sharedpreferences.contains(name))
      {
      if(sharedpreferences.contains(pass)){
         Intent i = new Intent(this,com.example.sessionmanagement.
         Welcome.class);
         startActivity(i);
      }
      }
      super.onResume();
   }

   public void login(View view){
      Editor editor = sharedpreferences.edit();
      String u = username.getText().toString();
      String p = password.getText().toString();
      editor.putString(name, u);
      editor.putString(pass, p);
      editor.commit();
      Intent i = new Intent(this,com.example.
      sessionmanagement.Welcome.class);
      startActivity(i);
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
   }

}

Here is the content of src/com.example.sessionmanagement/Welcome.java.

package com.example.sessionmanagement;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;

public class Welcome extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_welcome);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.welcome, menu);
      return true;
   }
   public void logout(View view){
      SharedPreferences sharedpreferences = getSharedPreferences
      (MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
      Editor editor = sharedpreferences.edit();
      editor.clear();
      editor.commit();
      moveTaskToBack(true); 
      Welcome.this.finish();
   }
   public void exit(View view){
      moveTaskToBack(true); 
      Welcome.this.finish();
   }
}

Here is the content of activity_main.xml.

<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"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <EditText
      android:id="@+id/editText2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/editText1"
      android:layout_below="@+id/textView2"
      android:ems="10"
      android:inputType="textPassword" >
   </EditText>

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_marginTop="52dp" 
      android:text="@string/Username"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:layout_alignTop="@+id/textView1"
      android:layout_marginRight="16dp"
      android:layout_marginTop="27dp"
      android:ems="10" >
      <requestFocus />
   </EditText>

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/textView1"
      android:layout_below="@+id/editText1"
      android:text="@string/Password"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/editText1"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="22dp"
      android:text="@string/Signin"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/editText2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="45dp"
      android:onClick="login"
      android:text="@string/Login" />

</RelativeLayout>

Here is the content of activity_welcome.xml.

<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"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".Welcome" >

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="146dp"
      android:onClick="logout"
      android:text="@string/logout" />

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/button1"
      android:layout_alignParentTop="true"
      android:layout_marginTop="64dp"
      android:text="@string/title_activity_welcome"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/button1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="43dp"
      android:onClick="exit"
      android:text="@string/exit" />

</RelativeLayout>

Here is the content of Strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">SessionManagement</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="Username">Username</string>
   <string name="Password">Password</string>
   <string name="Signin">Sign In</string>
   <string name="Login">Login</string>
   <string name="logout">Logout</string>
   <string name="title_activity_welcome">Welcome</string>
   <string name="exit">Exit without logout</string>

</resources>

Here is the content of AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sessionmanagement"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.sessionmanagement.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity
         android:name="com.example.sessionmanagement.Welcome"
         android:label="@string/title_activity_welcome" >
      </activity>
   </application>
</manifest>

Let's try to run your Session Management application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Anroid Session Management Tutorial

Type in your username and password (type anything you like, but remember what you type), and click on login button. It is shown in the image below:

Anroid Session Management Tutorial

As soon as you click on login button, you will be brought to this Welcome screen. Now your login information is stored in shared preferences.

Anroid Session Management Tutorial

Now click on Exit without logout button and you will be brought back to the home screen. This is shown in the image below:

Anroid Session Management Tutorial

Now Start the application again. And this time you will not be brought to the login screen, but directly to the welcome screen.This is shown in the image below:

Anroid Session Management Tutorial

Now click on logout button, and the application will be closed. Now open the application again, and since this time you logout your session, so you will be brought back to the front login screen. This is shown in the image below:

Anroid Session Management Tutorial

Advertisements
Advertisements