Wednesday, May 28, 2014

Android Session Management Using SharedPreferences

In this example creating login page fuctionality and save user data as like in session. After loging user will redirect to login screen and after back button click do not show login page. Using shared preferences to save and get user data globally through out the application


There are two ways to save data globally:

1. Save data in global variables:
If we are storing data in global variable , data will be lost once user closes the application.

2. Save the data in shared preferences:
If we are Storing data in shared preferences will be persistent to all application even after user closes the application. You can save key, value pair data in Shared preferences.


FILE : UserSessionManager.java
This class contain all user session related functions.
In this class file creating SharedPreferences and inserting / updating / deleting user session data from SharedPreferences.

further explanation given as comment in class code.
  1. package com.androidexample.usersessions;
  2. import java.util.HashMap;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.SharedPreferences;
  6. import android.content.SharedPreferences.Editor;
  7. public class UserSessionManager {
  8. // Shared Preferences reference
  9. SharedPreferences pref;
  10. // Editor reference for Shared preferences
  11. Editor editor;
  12. // Context
  13. Context _context;
  14. // Shared pref mode
  15. int PRIVATE_MODE = 0;
  16. // Sharedpref file name
  17. private static final String PREFER_NAME = "AndroidExamplePref";
  18. // All Shared Preferences Keys
  19. private static final String IS_USER_LOGIN = "IsUserLoggedIn";
  20. // User name (make variable public to access from outside)
  21. public static final String KEY_NAME = "name";
  22. // Email address (make variable public to access from outside)
  23. public static final String KEY_EMAIL = "email";
  24. // Constructor
  25. public UserSessionManager(Context context){
  26. this._context = context;
  27. pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
  28. editor = pref.edit();
  29. }
  30. //Create login session
  31. public void createUserLoginSession(String name, String email){
  32. // Storing login value as TRUE
  33. editor.putBoolean(IS_USER_LOGIN, true);
  34. // Storing name in pref
  35. editor.putString(KEY_NAME, name);
  36. // Storing email in pref
  37. editor.putString(KEY_EMAIL, email);
  38. // commit changes
  39. editor.commit();
  40. }
  41. /**
  42. * Check login method will check user login status
  43. * If false it will redirect user to login page
  44. * Else do anything
  45. * */
  46. public boolean checkLogin(){
  47. // Check login status
  48. if(!this.isUserLoggedIn()){
  49. // user is not logged in redirect him to Login Activity
  50. Intent i = new Intent(_context, LoginActivity.class);
  51. // Closing all the Activities from stack
  52. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  53. // Add new Flag to start new Activity
  54. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  55. // Staring Login Activity
  56. _context.startActivity(i);
  57. return true;
  58. }
  59. return false;
  60. }
  61. /**
  62. * Get stored session data
  63. * */
  64. public HashMap getUserDetails(){
  65. //Use hashmap to store user credentials
  66. HashMap user = new HashMap();
  67. // user name
  68. user.put(KEY_NAME, pref.getString(KEY_NAME, null));
  69. // user email id
  70. user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
  71. // return user
  72. return user;
  73. }
  74. /**
  75. * Clear session details
  76. * */
  77. public void logoutUser(){
  78. // Clearing all user data from Shared Preferences
  79. editor.clear();
  80. editor.commit();
  81. // After logout redirect user to Login Activity
  82. Intent i = new Intent(_context, LoginActivity.class);
  83. // Closing all the Activities
  84. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  85. // Add new Flag to start new Activity
  86. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  87. // Staring Login Activity
  88. _context.startActivity(i);
  89. }
  90. // Check for login
  91. public boolean isUserLoggedIn(){
  92. return pref.getBoolean(IS_USER_LOGIN, false);
  93. }
  94. }

FILE : LoginActivity.java

This is the first screen( Login screen ).
For Login using Username: admin and Password: admin
Using createUserLoginSession() to save user data in SharedPreferences for further use.
  1. package com.androidexample.usersessions;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.EditText;
  8. import android.widget.Toast;
  9. public class LoginActivity extends Activity {
  10. Button btnLogin;
  11. EditText txtUsername, txtPassword;
  12. // User Session Manager Class
  13. UserSessionManager session;
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_login);
  18. // User Session Manager
  19. session = new UserSessionManager(getApplicationContext());
  20. // get Email, Password input text
  21. txtUsername = (EditText) findViewById(R.id.txtUsername);
  22. txtPassword = (EditText) findViewById(R.id.txtPassword);
  23. Toast.makeText(getApplicationContext(),
  24. "User Login Status: " + session.isUserLoggedIn(),
  25. Toast.LENGTH_LONG).show();
  26. // User Login button
  27. btnLogin = (Button) findViewById(R.id.btnLogin);
  28. // Login button click event
  29. btnLogin.setOnClickListener(new View.OnClickListener() {
  30. @Override
  31. public void onClick(View arg0) {
  32. // Get username, password from EditText
  33. String username = txtUsername.getText().toString();
  34. String password = txtPassword.getText().toString();
  35. // Validate if username, password is filled
  36. if(username.trim().length() > 0 && password.trim().length() > 0){
  37. // For testing puspose username, password is checked with static data
  38. // username = admin
  39. // password = admin
  40. if(username.equals("admin") && password.equals("admin")){
  41. // Creating user login session
  42. // Statically storing name="Android Example"
  43. // and email="androidexample84@gmail.com"
  44. session.createUserLoginSession("Android Example",
  45. "androidexample84@gmail.com");
  46. // Starting MainActivity
  47. Intent i = new Intent(getApplicationContext(), MainActivity.class);
  48. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  49. // Add new Flag to start new Activity
  50. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  51. startActivity(i);
  52. finish();
  53. }else{
  54. // username / password doesn't match&
  55. Toast.makeText(getApplicationContext(),
  56. "Username/Password is incorrect",
  57. Toast.LENGTH_LONG).show();
  58. }
  59. }else{
  60. // user didn't entered username or password
  61. Toast.makeText(getApplicationContext(),
  62. "Please enter username and password",
  63. Toast.LENGTH_LONG).show();
  64. }
  65. }
  66. });
  67. }
  68. }

FILE : activity_login.xml

This file is used as layout file in LoginActivity.java.
It will create login screen design.
<LinearLayout 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:orientation="vertical"
    android:padding="10dip">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username (Enter 'admin')"
        android:singleLine="true"
        android:layout_marginBottom="5dip"/>
     
    <EditText android:id="@+id/txtUsername"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"/>
     
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Password (Enter 'admin')"
        android:layout_marginBottom="5dip"/>
     
    <EditText android:id="@+id/txtPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:password="true"
        android:singleLine="true"/>
     
    <Button android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login"/>
</LinearLayout>

FILE : MainActivity.java

This is the welcome screen after user login.
Get user data from SharedPreferences and show on activity.

  1. package com.androidexample.usersessions;
  2. import java.util.HashMap;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.text.Html;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.TextView;
  9. import android.widget.Toast;
  10. public class MainActivity extends Activity {
  11. // User Session Manager Class
  12. UserSessionManager session;
  13. // Button Logout
  14. Button btnLogout;
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. // Session class instance
  20. session = new UserSessionManager(getApplicationContext());
  21. TextView lblName = (TextView) findViewById(R.id.lblName);
  22. TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
  23. // Button logout
  24. btnLogout = (Button) findViewById(R.id.btnLogout);
  25. Toast.makeText(getApplicationContext(),
  26. "User Login Status: " + session.isUserLoggedIn(),
  27. Toast.LENGTH_LONG).show();
  28. // Check user login (this is the important point)
  29. // If User is not logged in , This will redirect user to LoginActivity
  30. // and finish current activity from activity stack.
  31. if(session.checkLogin())
  32. finish();
  33. // get user data from session
  34. HashMap user = session.getUserDetails();
  35. // get name
  36. String name = user.get(UserSessionManager.KEY_NAME);
  37. // get email
  38. String email = user.get(UserSessionManager.KEY_EMAIL);
  39. // Show user data on activity
  40. lblName.setText(Html.fromHtml("Name: " + name + ""));
  41. lblEmail.setText(Html.fromHtml("Email: " + email + ""));
  42. btnLogout.setOnClickListener(new View.OnClickListener() {
  43. @Override
  44. public void onClick(View arg0) {
  45. // Clear the User session data
  46. // and redirect user to LoginActivity
  47. session.logoutUser();
  48. }
  49. });
  50. }
  51. }

FILE : activity_login.xml

This file is used as layout file in MainActivity.java.
It will create Welcome screen (after login) design.
<LinearLayout 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:orientation="vertical"
        android:padding="10dip">
         
        
        <TextView
            android:id="@+id/lblName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:layout_marginTop="40dip"
            android:layout_marginBottom="10dip"/>
     
         
        <TextView
            android:id="@+id/lblEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:layout_marginBottom="40dip"/>
         
         
        <Button android:id="@+id/btnLogout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Logout"/>
     
    </LinearLayout>


No comments:

Post a Comment