Session are useful when you want to store user data globally through out the application. This can be done in two ways. One is storing them in a global variables and second is storing the data in shared preferences. The problem with storing data in global variable is data will be lost once user closes the application, but storing the data in shared preferences will be persistent even though user closes the application.

Download Code

Application shared preferences allows you to save and retrieve key, value pair data. Before getting into tutorial, I am giving basic information needed to work with shared preferences.

Initialization

Application shared preferences can be fetched using getSharedPreferences() method.You also need an editor to edit and save the changes in shared preferences. The following code can be used to get application shared preferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

Storing Data

You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long

editor.commit(); // commit changes

Retrieving Data

Data can be retrived from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences not on Editor.

// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Clearing / Deleting Data

If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email

editor.commit(); // commit changes

Following will clear all the data from shared preferences

editor.clear();
editor.commit(); // commit changes

The following is a simple tutorial which will have a login form and a dashboard screen. At first user will login using login details and once he successfully logged in his credentials (name, email) will be stored in shared preferences.

——————————————————————————————————————————————————-

User Session Management using Shared Preferences

1. Create a new project in Eclipse IDE File โ‡’ New โ‡’ Android Application Project and fill all the required details
2. I am adding alert dialog manager class to show alert messages while validating the login form. Create a new class and name it as AlertDialogManager.java and paste the following code.

package com.androidhive.sessions;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
 
public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
 
        // Setting Dialog Title
        alertDialog.setTitle(title);
 
        // Setting Dialog Message
        alertDialog.setMessage(message);
 
        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
 
        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
    }
}

3. I am writing all session related functions in one class to make them available in all activities. Create a new class named SessionManagement.java and add following lines of code

package com.androidhive.sessions;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {
	// Shared Preferences
	SharedPreferences pref;
	
	// Editor for Shared preferences
	Editor editor;
	
	// Context
	Context _context;
	
	// Shared pref mode
	int PRIVATE_MODE = 0;
	
	// Sharedpref file name
	private static final String PREF_NAME = "AndroidHivePref";
	
	// All Shared Preferences Keys
	private static final String IS_LOGIN = "IsLoggedIn";
	
	// User name (make variable public to access from outside)
	public static final String KEY_NAME = "name";
	
	// Email address (make variable public to access from outside)
	public static final String KEY_EMAIL = "email";
	
	// Constructor
	public SessionManager(Context context){
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

4. In this example i am storing login status, name, email in shared preferences, so i added a function called createLoginSession(String name, String email) to SessionManagement class. Add the following function to SessionManagement.java.

> This function simply stores login status(true), name, email in shared preferences.

/**
	 * Create login session
	 * */
	public void createLoginSession(String name, String email){
		// Storing login value as TRUE
		editor.putBoolean(IS_LOGIN, true);
		
		// Storing name in pref
		editor.putString(KEY_NAME, name);
		
		// Storing email in pref
		editor.putString(KEY_EMAIL, email);
		
		// commit changes
		editor.commit();
	}

5.In order to get the stored preferences data, I added a function called getUserDetails() with the following code.

> The following function will read shared preferences and returns user data in HashMap

/**
	 * Get stored session data
	 * */
	public HashMap<String, String> getUserDetails(){
		HashMap<String, String> user = new HashMap<String, String>();
		// user name
		user.put(KEY_NAME, pref.getString(KEY_NAME, null));
		
		// user email id
		user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
		
		// return user
		return user;
	}

6. To check whether user logged in or not i added a function checkLogin() which you can call in all Activities to check user login status.

> This function simply check user login status from shared preferences and if user is not login it will redirect user to LoginActivity

/**
	 * Check login method wil check user login status
	 * If false it will redirect user to login page
	 * Else won't do anything
	 * */
	public void checkLogin(){
		// Check login status
		if(!this.isLoggedIn()){
			// user is not logged in redirect him to Login Activity
			Intent i = new Intent(_context, LoginActivity.class);
			// Closing all the Activities
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			
			// Add new Flag to start new Activity
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			// Staring Login Activity
			_context.startActivity(i);
		}
		
	}

7. Add a function called logoutUser() to clear all the data from shared preferences. Call this function when you want to logout the user.

> This function clears all session data and redirect the user to LoginActivity

/**
	 * Clear session details
	 * */
	public void logoutUser(){
		// Clearing all data from Shared Preferences
		editor.clear();
		editor.commit();
		
		// After logout redirect user to Loing Activity
		Intent i = new Intent(_context, LoginActivity.class);
		// Closing all the Activities
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		
		// Add new Flag to start new Activity
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		// Staring Login Activity
		_context.startActivity(i);
	}

Final Code

package com.androidhive.sessions;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {
	// Shared Preferences
	SharedPreferences pref;
	
	// Editor for Shared preferences
	Editor editor;
	
	// Context
	Context _context;
	
	// Shared pref mode
	int PRIVATE_MODE = 0;
	
	// Sharedpref file name
	private static final String PREF_NAME = "AndroidHivePref";
	
	// All Shared Preferences Keys
	private static final String IS_LOGIN = "IsLoggedIn";
	
	// User name (make variable public to access from outside)
	public static final String KEY_NAME = "name";
	
	// Email address (make variable public to access from outside)
	public static final String KEY_EMAIL = "email";
	
	// Constructor
	public SessionManager(Context context){
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}
	
	/**
	 * Create login session
	 * */
	public void createLoginSession(String name, String email){
		// Storing login value as TRUE
		editor.putBoolean(IS_LOGIN, true);
		
		// Storing name in pref
		editor.putString(KEY_NAME, name);
		
		// Storing email in pref
		editor.putString(KEY_EMAIL, email);
		
		// commit changes
		editor.commit();
	}	
	
	/**
	 * Check login method wil check user login status
	 * If false it will redirect user to login page
	 * Else won't do anything
	 * */
	public void checkLogin(){
		// Check login status
		if(!this.isLoggedIn()){
			// user is not logged in redirect him to Login Activity
			Intent i = new Intent(_context, LoginActivity.class);
			// Closing all the Activities
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			
			// Add new Flag to start new Activity
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			// Staring Login Activity
			_context.startActivity(i);
		}
		
	}
	
	
	
	/**
	 * Get stored session data
	 * */
	public HashMap<String, String> getUserDetails(){
		HashMap<String, String> user = new HashMap<String, String>();
		// user name
		user.put(KEY_NAME, pref.getString(KEY_NAME, null));
		
		// user email id
		user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
		
		// return user
		return user;
	}
	
	/**
	 * Clear session details
	 * */
	public void logoutUser(){
		// Clearing all data from Shared Preferences
		editor.clear();
		editor.commit();
		
		// After logout redirect user to Loing Activity
		Intent i = new Intent(_context, LoginActivity.class);
		// Closing all the Activities
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		
		// Add new Flag to start new Activity
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		// Staring Login Activity
		_context.startActivity(i);
	}
	
	/**
	 * Quick check for login
	 * **/
	// Get Login State
	public boolean isLoggedIn(){
		return pref.getBoolean(IS_LOGIN, false);
	}
}

8. Until now we are done creating Session Management class and now we are going to learn how to use this class in your application. For this create a simple login form asking username, password.

Create a layout xml file and a class to create login form. Name the xml file as activity_login.xml and class name as LoginActivity.java

<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">

   	<!-- Email Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username (Enter 'test')"
        android:singleLine="true"
        android:layout_marginBottom="5dip"/>
    
    <!-- Email input text -->
    <EditText android:id="@+id/txtUsername"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"/>
    
    <!-- Password Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Password (Enter 'test')"
        android:layout_marginBottom="5dip"/>
    
    <!-- Password input text -->
    <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"/>
    
    <!-- Login button -->
    <Button android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login"/>

</LinearLayout>

For testing purpose i am checking username, password as test, test.

Once the user enters correct login details a session will be created by calling session.createLoginSession(“Android Hive”, “anroidhive@gmail.com”) and user is redirected to MainActivity.

package com.androidhive.sessions;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	
	// Email, password edittext
	EditText txtUsername, txtPassword;
	
	// login button
	Button btnLogin;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Session Manager Class
	SessionManager session;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login); 
        
        // Session Manager
        session = new SessionManager(getApplicationContext());                
        
        // Email, Password input text
        txtUsername = (EditText) findViewById(R.id.txtUsername);
        txtPassword = (EditText) findViewById(R.id.txtPassword); 
        
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
        
        
        // Login button
        btnLogin = (Button) findViewById(R.id.btnLogin);
        
        
        // Login button click event
        btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// Get username, password from EditText
				String username = txtUsername.getText().toString();
				String password = txtPassword.getText().toString();
				
				// Check if username, password is filled				
				if(username.trim().length() > 0 && password.trim().length() > 0){
					// For testing puspose username, password is checked with sample data
					// username = test
					// password = test
					if(username.equals("test") && password.equals("test")){
						
						// Creating user login session
						// For testing i am stroing name, email as follow
						// Use user real data
						session.createLoginSession("Android Hive", "anroidhive@gmail.com");
						
						// Staring MainActivity
						Intent i = new Intent(getApplicationContext(), MainActivity.class);
						startActivity(i);
						finish();
						
					}else{
						// username / password doesn't match
						alert.showAlertDialog(LoginActivity.this, "Login failed..", "Username/Password is incorrect", false);
					}				
				}else{
					// user didn't entered username or password
					// Show alert asking him to enter the details
					alert.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter username and password", false);
				}
				
			}
		});
    }        
}
android session login form
android login failed

9. After user redirected to MainActivity, I am getting stored session data by calling getUserDetails() and displayed in textviews.

> session.checkLogin() is called to check user login status. Here if user is not login he will be redirected to LoginActivity.java
> If user is logged in, user details are fetched by calling session.getUserDetails() and displayed in textviews.
> Also I have logout button which invokes a function session.logoutUser() to clear the session data.
Layout code for activity_main.xml

<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">
    
    <!-- Name Label -->
    <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"/>

   	<!-- Email Label -->
    <TextView
        android:id="@+id/lblEmail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:layout_marginBottom="40dip"/>
    
    <!-- Button to show session data -->
    <Button android:id="@+id/btnLogout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Logout"/>
</LinearLayout>

Code for MainActivity.java

package com.androidhive.sessions;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Session Manager Class
	SessionManager session;
	
	// Button Logout
	Button btnLogout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Session class instance
        session = new SessionManager(getApplicationContext());
        
        TextView lblName = (TextView) findViewById(R.id.lblName);
        TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
        
        // Button logout
        btnLogout = (Button) findViewById(R.id.btnLogout);
        
        Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
        
        
        /**
         * Call this function whenever you want to check user login
         * This will redirect user to LoginActivity is he is not
         * logged in
         * */
        session.checkLogin();
        
        // get user data from session
        HashMap<String, String> user = session.getUserDetails();
        
        // name
        String name = user.get(SessionManager.KEY_NAME);
        
        // email
        String email = user.get(SessionManager.KEY_EMAIL);
        
        // displaying user data
        lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
        lblEmail.setText(Html.fromHtml("Email: <b>" + email + "</b>"));
        
        
        /**
         * Logout button click event
         * */
        btnLogout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// Clear the session data
				// This will clear all session data and 
				// redirect user to LoginActivity
				session.logoutUser();
			}
		});
    }
        
}
android user session data

10. Open AndroidManifest.xml file, add the following code and run the project.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.sessions"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="Dashboard Screen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- DashBoard / MainActivity -->
        <activity
            android:name=".LoginActivity"
            android:label="User Login" >
        </activity>
    </application>

</manifest>
android user session management
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Thank you very much..!

  • heraldo

    very helpful info ravi..helps alot..especially new to android

  • ZHicham

    how to handle sessions from php web pages inside webview

  • haozhenxiao

    What a remarkable tutorial,thank you very much.

  • venkat

    Hello Ravi am new to android.. i have problem with my SessionManagement.java followed by ur SessionManagement.java .. In my SessionManagemn.java., i stored
    3 data ip,username,password from loginActivity.java but when am getting those data 3 values in MainActivity.java it returning ip address value only..

    i think it is nice post of beginners..

  • Om

    Hi Ravi Sir,

    Your all tutorials are the best examples of excellency and brilliancy in android.
    keep it up !

    • Samarth Mishra

      Hey I am new to android. I find all these tutorials and applicaiions so great.
      I really want a little help here. Whatever code I am downloading is showing a “Project has no default.properties file! Edit the project properties to set one”
      Error. What should I do?

  • andcsie

    Is this code available if i use a Sqlite database?
    Thank you!

  • felix

    So, what you recommend to managment the session???? Thanks!!!

  • Samarth Mishra

    Hey I am new to android. I find all these tutorials and applicaiions so great.
    I really want a little help here. Whatever code I am downloading is showing a “Project has no default.properties file! Edit the project properties to set one”
    Error. What should I do?

  • Kent

    I also have the same problem, if you solved it, help me please

  • kumaran

    thanks a lot. . . .

  • Parvindra Singh Shekhawat

    i realy feel great when i use this tutorial …. your work is amazing nd marvless…. nice …. it helps me very much …. to improve my programing skills

  • Samarth Mishra

    Hey I am new to android. I find all these tutorials and applications so great.
    I really want a little help here. Whatever code I am downloading is showing a “Project has no default.properties file! Edit the project properties to set one”
    Error. What should I do?

  • Zain

    Thanks is small word to say… Bro u did a good job… save us and much more ๐Ÿ™‚

  • Rohan Poddar

    Nice Job. The class is very nicely written and very useful.

  • This helped me out more than you know. This may have been simple, but was perfect for what I needed in order to come up with my own solitions. Thanks.

  • manish

    hi…
    how can i get the the value from button and set on edit text in same activity..plz mind the value is not parmanently stored…

  • temp

    when I make calls to the server, how can I know that the calls came from a particular user and not anyone else?

  • phyllis Wanjiru

    hey your tutorials are very helpfull, am working on a small system and need help with the sqlite db..

  • Hima Javvadi

    In an online test were we are using one list for 7 questions where one layout with two questions repeating in the loop,for next set of questions, my radio buttons and check box once selected for few question and next going back and clicking selected answers are changed : any solution can you refer

    • Mofe-hendy Ejegi

      try storing the selected answers in a framework, such as a list, or map. then whenever you return to a previously answered question, make a call to that list or map, to get the previously selected answer, then based on the answer, use the setSelected(true) function on the corresponding radio button

  • M.S.

    Thanks so much for your all useful tutorials.

  • shakeeb hussain

    Excellent Work …

    • sameer

      Nice Code Thanx.,

  • Edogawa Conan

    thank you very much

  • Balaji D

    in MainActivity, after the line

    session.checkLogin();

    check for the condition

    if (!session.isLoggedIn()) {
    finish();
    }

  • Boy

    I found a problem when pressing “back” button at login screen. It will bring me to main screen without logging in.

    • Galih

      you just need a little modify of that’s code. ๐Ÿ™‚

      • syndy

        what modification should be done for that?

        • anwar

          @Override

          public void onBackPressed() {

          Log.d(“CDA”, “onBackPressed Called”);

          Intent setIntent = new Intent(Intent.ACTION_MAIN);

          setIntent.addCategory(Intent.CATEGORY_HOME);

          setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

          startActivity(setIntent);

          finish();

          }

          dis will work

      • Banny

        I’ve got the same problem! help me

        • Yakhtar Ali

          Put this code in your Login class

          @Override
          public void onBackPressed() {
          finish();
          }

          • anwar

            still same result.. pls help!

  • Anony

    why there is isLoggedIn() method on checkLogin() method even though you don’t declare any isLoggedIn()?

    • Galih

      because the value of ‘pref’ has been edited using ‘editor’
      you must see ‘editor.putBoolean(IS_LOGIN, true);’ to assign, and pref.getBoolean(IS_LOGIN,false). to get the value.

      • aik

        i dont understand

  • Andy

    Good tutorial. Shouldn’t SessionManager be singleton? We are crating a “new SessionManager” object in every activity of the app. Is that necessary.

  • ado

    good and how make registration?

  • syndy

    Thanks for this helpful tutorial, but when pressing “back” button after logging in, it is not clearing the text of username and password entered by the user, how to do that?

    • Thahzan Mohomed

      You probably figured it out already, but here goes. You can clear the 2 EditTexts in the OnClickListener of the Login button.

      txtUserName.setText(“”);
      txtPassword.setText(“”);

      But it will be a good idea to stop the user from going back to the login screen by pressing the back button. You can do this by the following code

      @Override
      public void onBackPressed() {
      //Some stuff (Toast or something saying “You shall not pass”)
      }

  • Banny

    Thanks por this tutorial, but i have a question: When I press back button, my application returns to previous activity, you help me, please.

    • Yakhtar Ali

      Put this code in your Login class

      @Override
      public void onBackPressed() {
      finish();
      }

      • Banny

        Thanks a lot!

  • dev

    Hi Ravi, will u please tell me how to maintain session time in application.

  • Jet

    this works fine for me, just need to change the IP address.. and this is EXACTLY what im looking for, thanks for the tutorial!!!!!!

  • Karthika J

    nice explanation..this works for me.. thanks ๐Ÿ™‚

  • thanks for sharing… it’s very helpful ๐Ÿ™‚

  • Oliva Valle

    Excelente post, me ayudo mucho

  • Thanks man, this is useful

  • Cristhian Camilo

    This is really helpful. Thanks for sharing, I hope you upload more tutorials with different methods in order to save sessions in apps. For now, I will use this :):)

  • Archana Belote

    nice….its works..

  • Asif Hingora

    Excellent very useful..

    • patel maulik

      hmm

  • Sara

    Hi! Thanks for sharing. I am new to android, I have a question. How to display value such as username, age from MySQL on activity_main.xml after login ?

  • Stikozo

    Is it possible to create a button for the user to be able to post data to a listview and be able to delete it??? If so can you please give me a little details or a tutorial reference ?

    Thank you in advance

  • bsoykal

    Good job dude ๐Ÿ˜‰

  • NUR ARIF PRIHUTOMO

    Found wrong code on Session class, there is addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) for kill all activities, it must be Intent.FLAG_ACTIVITY_CLEAR_TASK.

  • Gustavo Rozolin

    thanks you a lot of, your pega help me to make my firts Android App. https://play.google.com/store/apps/details?id=com.uifiu.android

    • Yan

      Are you promotion your app?hah

  • Rgarcia

    Very helpfull tutorial. Thank you.

  • Yara

    All your tutorials are helpful. Thank you very much.

  • Anh Le Hoang

    It was very useful. Thanks for sharing.

  • Afshaan Shaikh

    Its a very useful example. thank you soo much…
    Can u let me know how to connect the same with mysql database?

  • Mary Mose

    Very helpful but ฤฑ have a question if i make LoginActivity extends fragment how could i access the name and password

  • Why a hashmap instead of a User object?

    • You can’t store the object directly. May be you can use gson to convert the object to json and store, convert the json back to object while retrieving.

  • Sudheesh Mohan

    After logout , when I press back it goes back to the MainActivity without logging in. Then I replaced i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); with

    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); and it worked fine!

  • Slim tt

    Good tutorial. Shouldn’t SessionManager be singleton? We are crating a “new SessionManager” object in every activity of the app. Is that necessary ?

    • Kiwi Choe

      No answer…. you used sigleton Slim tt??

  • shajeeha khalid

    hello sir, I am new in android even in development plzzz tell me I want to change test as username and password and want to login through user defined username and password.

  • hamzaabsi

    Bad tutorial , if user in login activity and press back redirect me to main activity , big problem

    • Rajeev .Tapadar

      to get rid of that situation please use this:
      @Override
      public void onBackPressed() {
      moveTaskToBack(true);
      }

      In your LoginActivity.java file

  • Prasanna Blaze

    i am getting error on the line…
    if(!this.isLoggedIn())
    it is asking me to create new method called isLoggedIn

    • prathap badavath

      did you create isLoggedIn() method in SessionManager.java?
      check it once.

  • hrishi

    hi m new in android I followed this tutorial but facing problem my activity not called, if User Login status false then i set SignIn activity but its not working and displaying white screen repeating again n again continious.. plz help…

  • Patel Jack

    hello sir.i want to edit data of currently logged in user which is in mysql database so can you please suggest me what to do for that or anyone know please help me…

    • Atif Patel

      Did u got the solution..?

  • teja

    when i closed the app and opened it i am getting my login page
    ?

  • teja

    my login session is lost.how to save it?help

  • NeErAj KuMaR

    I use same code but when setText of username and Email ID in DashBoard activity then get null exception on username.setText(name) line or second problem is that is always give same problem not going login page before that error

    • Give me your shared preferences code

      • NeErAj KuMaR

        package com.demo.neeraj;

        import android.content.Context;

        import android.content.Intent;

        import android.content.SharedPreferences;

        import com.demo.neeraj.auth.Login;

        import java.util.HashMap;

        public class SessionManagement {

        SharedPreferences pref;

        // Editor for Shared preferences

        SharedPreferences.Editor editor;

        // Context

        Context _context;

        // Shared pref mode

        int PRIVATE_MODE = 0;

        // Sharedpref file name

        private static final String PREF_NAME = “Demo”;

        // All Shared Preferences Keys

        private static final String IS_LOGIN = “IsLoggedIn”;

        // User name (make variable public to access from outside)

        public static final String KEY_NAME = “name”;

        // Email address (make variable public to access from outside)

        public static final String KEY_EMAIL = “email”;

        // Constructor

        public SessionManagement(Context context) {

        this._context = context;

        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

        editor = pref.edit();

        }

        public void createLoginSession(String name, String email) {

        // Storing Login value as TRUE

        editor.putBoolean(IS_LOGIN, true);

        editor.putString(KEY_NAME, name);

        // Storing email in pref

        editor.putString(KEY_EMAIL, email);

        // commit changes

        editor.commit();

        }

        /**

        * Check Login method wil check user Login status

        * If false it will redirect user to Login page

        * Else won’t do anything

        */

        public void checkLogin() {

        // Check Login status

        if (!this.isLoggedIn()) {

        // user is not logged in redirect him to Login Activity

        Intent i = new Intent(_context, Login.class);

        // Closing all the Activities

        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity

        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity

        _context.startActivity(i);

        }

        }

        /**

        * Get stored session data

        */

        public HashMap getUserDetails() {

        HashMap user = new HashMap();

        // user name

        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id

        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

        // return user

        return user;

        }

        /**

        * Clear session details

        */

        public void logoutUser() {

        // Clearing all data from Shared Preferences

        editor.clear();

        editor.commit();

        // After logout redirect user to Login Activity

        Intent i = new Intent(_context, Login.class);

        // Closing all the Activities

        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity

        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity

        _context.startActivity(i);

        }

        /**

        * Quick check for Login

        **/

        // Get Login State

        public boolean isLoggedIn() {

        return pref.getBoolean(IS_LOGIN, false);

        }

        }

        it is same code as you provide of shared Preference.

        Dashboard Code :

        protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_drawer_main);

        session = new SessionManagement(DrawerMainActivity.this);

        session.checkLogin();

        HashMap user = session.getUserDetails();

        email = user.get(SessionManagement.KEY_EMAIL);

        name = user.get(SessionManagement.KEY_NAME);

        fullName = (TextView) header.findViewById(R.id.fullname_main);

        emailID = (TextView) header.findViewById(R.id.email_id_main);

        fullName.setText(name);

        emailID.setText(email);

        }

        • Have you imported the textview in activity using findViewById() for username?

    • Vinod

      I see the same problem. For some reason it is unable to find any view using findViewById

      • Vinod

        Nevermind, I had set the content view of some other activity, hence could not find the view.

  • Prakash Rawat

    i have imported your code in my android studio.everything is working fine but when i tried to register in gennymotion app got crashed with the log cat view

    FATAL EXCEPTION: main
    Process: info.androidhive.loginandregistration, PID: 2800
    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference
    at com.android.volley.Request.(Request.java:136)
    at com.android.volley.toolbox.StringRequest.(StringRequest.java:43)
    at info.androidhive.loginandregistration.activity.RegisterActivity$5.(RegisterActivity.java:173)
    at info.androidhive.loginandregistration.activity.RegisterActivity.registerUser(RegisterActivity.java:118)
    at info.androidhive.loginandregistration.activity.RegisterActivity.access$300(RegisterActivity.java:35)
    at info.androidhive.loginandregistration.activity.RegisterActivity$1.onClick(RegisterActivity.java:84)
    at android.view.View.performClick(View.java:4756)
    at android.view.View$PerformClick.run(View.java:19749)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

  • Ashok

    i am getting error when i close my application and restart it main page error contains username and password is null

  • Jaber p.m.r

    Hi
    After logout just try pushing the back btn from navigation bar!
    you can go back to dashboard without enter username and password

  • Shankar Ganesh

    Hi sir,
    Whenever i launch the app from apps menu its shows the login screen only, even login status is true(i checked the login status by using “Toast”) Toast shows login status as true. Is there any solution to hide the login activity after logged in???

    • Paste your login activity code here

      • Udit Patel

        Yes, Code as per you given.

        • Atika

          Did u get the solutions ??

  • Saumik

    Excellent post..it is very helpful ๐Ÿ™‚

  • vinod

    sir, can we apply typeface attribute (telugu fonts) for the strings in the android code.
    my code is:
    mPlanetTitles = new String[]{“Login”, “Register”, “Aboutus”,”Suggetions”,”Ratings”,”address”,”callcenter”,”complaints”,”Share”,”Formers”,”Seeds”,”Wetherreport”};

  • Haritha Gupta Ramini

    Hey ! This tutorial is so helpful ! how to work with the token and sessions ?? do you have any tutorial for that too ?

  • Ravi Shankar Verma

    I passed a String in
    session.createLoginSession(“12345String”);

    But it shows following Exception

    java.lang.NullPointerException

    at LoginActivity$UserLoginTask.onPostExecute(LoginActivity.java:334)

    why is it not creating session?

  • Karthi9474@gmail.com

    how to make an automatic session expire when userinactive after 15 min

  • Luis Troya

    If I want to redirect the logged user, will be this archieve on this line right?

    Toast.makeText(getApplicationContext(), “User Login Status: ” + session.isLoggedIn(), Toast.LENGTH_LONG).show();

  • aviroop sanyal

    if I want to generalize the userName, password being passed, then what should I do

  • Karthi9474@gmail.com

    great tutorial RAVI thanks i need an relevant information about session automatic logout when user idle state in fragment

    send me any example

    thanks

  • Margot Le Rouzic

    Is it possible to avoid the deleteUsers function in the logout and having the right fetching user details ? (because I don’t want to drop my table due to the foreign key with another table) Thanks a lot for this tutorial !!

  • Arjun K Dev

    session.isLoggedIn() showing “true” in my code even after clearing background running…..but leading to login activity every time…..

  • Amit Chhatbar

    How can I verify stored Email id as username and Password in the Database? I want to Login this way. Please help.

  • Huda Zawawi

    thanks.. great tutorial. i’m using android studio.

    success without error.

  • shahrukh

    i got error in session manager call

  • shahrukh

    it require me to create a session manager class what i do???

  • Ahmad Zaki Robbany M

    great post. can i ask? why i can’t put session = new SessionManager(getApplicationContext()); in my database adapter? can you help?

    • Ibrahim Samad

      You can’t get the ApplicationContext() when you are inside your database Adapter. You have to create a class that extends Application, override its onCreate() method and set the getApplicationContext() there. You can then create a method that returns this instance. Take a look at this:

      public class ContextGetter extends Application {

      private static Context context;

      @Override
      public void onCreate() {
      super.onCreate();
      context = getApplicationContext();
      }

      public static Context getAppContext(){
      return context;
      }
      }

      Now, you can then pass ContextGetter.getAppContext() in the session Manager constructor and it will work without errors. Hope this helps.

  • Joan

    Hello, Thanks for the tutorial. I have a problem. If a remove the app from the recet app and re open it. It always send me to the login. The user login status alway say false. Why? I want to remove the data only when te user log out. If he kill the app when the app is re open has to read the shared preference and go to the main activity

  • GereltOd

    Your file name is SessionManagement.java. But class name is SessionManager. Fix that for new learners.

    • Paraskumar

      thanks this was helpful

    • 128 Sample Packs

      a Year later and he still didn’t fix it…

  • Laxman Basawa

    These snippets are really helpful. Thanks. understanding better…

  • Adel Abdallah

    So clear and helpful.. thanks

  • SARAVANAN

    Hi ,

    Android Session concept we will use only Shared preference .Why ? Any other Choice ?

  • Angie Loo

    I’m a total newbie to Android. Thanks for this awesome tutorial!

  • Saathwik Nalige

    Thanks for this awesome tutorial…!!!

  • tochukwu christian

    I really want to comment you for a job well done. but i seem to be having issues with this>>>>>>>>>>>Toast.makeText(getApplicationContext(), “User Login Status: ” + session.isLoggedIn(), Toast.LENGTH_LONG).show();……..especially this>>>>session.isLoggedIn(), its showing red depicting there’s an error. pls help.

  • Cyril

    Nice tutorial!

    How do these work if KEY_NAME & KEY_EMAIL are private in SessionManager?
    // name
    String name = user.get(SessionManager.KEY_NAME);
    // email
    String email = user.get(SessionManager.KEY_EMAIL);

    • You can not access a private variable outside its class according to java concepts. you have to make them public.
      and then do
      String name= mSessionManager.getUserDetails().get(SessionManager.KEY_NAME)

  • Mateen Sheikh

    Thanks man! your tutorial really helped.

  • Shameem Ahsan

    sir,have fragments not activity what to do in in checklogin function in sessionmanager

  • fatema akter

    logout is not logging out the user. When i press the back button it again returns to the previous activity. Shared Preferences data is also not removing

  • Sunil Kumar

    In the Intent Filter LoginActivity should in place of MainActivity, bcz first of the all LoginActivity is running.
    No code description about R.drawable.success and fail. ” alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);”

  • Ankit Palli

    Great Ravi,
    Super tutorial i have implemented one in my app thank you ssooo much..

    http://www.ankitpalli.com/2017/04/what-is-sharedpreferences-and-how-to.html

  • Oormila Ghantasala

    I am new to android. I have implemented the same code with some changes so that it suits my requirements. But my app gets closed everytime saying “Unfortunately app stopped”. Please help me