Android Working with User Sessions

In this post, I will describe how to manage user session using shared preferences.Using shared preferences we can store user credentials and next time when a user comes to use application we check if the values in shared preferences are available the instead of prompting the user for login we open home activity.

So, Let’s start

1.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.Let’s see how shared preferences are used to store and retrieve the values.

Storing the values in Shared Preferences

  SharedPreferences coderzpassionprefer=context.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=coderzpassionprefer.edit();
// for string
editor.putString(key,key_value);
//for int
editor.putInt(key,key_value);
//for boolean
editor.putBoolean(key,key_value);
//then commit 
editor.commit();

Getting the values from Shared Preferences

SharedPreferences coderzpassionprefer=context.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=coderzpassionprefer.edit();
// getting string
editor.getString(key,default_valueifvaluenotstored);
//getting int
editor.getInt(key,default_valueifvaluenotstored);
//getting boolean
editor.getBoolean(key,default_valueifvaluenotstored);

Deleting data from Shared Preferences

//deleting the key
editor.remove(key);
// then commit
editor.commit();

Clear the values from Shared Preferences

//clear the values
editor.clear();
//then commit
editor.commit();

So, Let’s Start

3.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

4. we will create CoderzPassionSession.java to manage all Shared Preferences related operations.

CoderzPassionSession.java

package com.coderzpassion.usersessionsample;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.EditText;

/**
 * Created by coderzpassion on 03/03/16.
 */
public class CoderzPassionSession {
    //key for username
    private String USERNAME="username";
    //key for password
    private String PASSWORD="password";
    //key for email
    private String EMAIL="email";
    //key for preferences
    private String PREFERENCES="coderzpassion";
    //key for is user login
    private String ISLOGIN="login";
    // Shared Preferences variable
    SharedPreferences coderzpassionprefer;
    //editor for shared preference
    SharedPreferences.Editor editor;

    public CoderzPassionSession(Context context)
    {
        coderzpassionprefer=context.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
        editor=coderzpassionprefer.edit();

    }
    // function store user details
    public void storeUser(String name,String pass,String email)
    {
        editor.putString(USERNAME,name);
        editor.putString(PASSWORD,pass);
        editor.putString(EMAIL,email);
        editor.commit();
    }
    // to login user
    public void loginUser(String name,String password,boolean login)
    {
        editor.putString(USERNAME,name);
        editor.putString(PASSWORD,password);
        editor.putBoolean(ISLOGIN,login);
        editor.commit();
    }

    //to get username
    public String getUserName()
    {

        return coderzpassionprefer.getString(USERNAME,"");
    }
    //to get userpassword
    public String getUserPassword()
    {
        return coderzpassionprefer.getString(PASSWORD,"");

    }
    //to get useremail
    public String getUserEmail()
    {
        return coderzpassionprefer.getString(EMAIL,"");
    }
    //to check whether user is login or not
    public boolean isUserLogedIn()
    {
        return coderzpassionprefer.getBoolean(ISLOGIN,false);
    }
    // to delete the user and clear the preferences
    public void logOutUser()
    {
        editor.clear();
        editor.commit();
    }
    
}

5. Now we create a layout for MainActivity.java for signup.

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

    <TextView
        android:text="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign Up"/>

</LinearLayout>

6. Now create a MainActivity.java for user to signup

MainActivity.java

package com.coderzpassion.usersessionsample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText name,email,password;
    Button signup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final CoderzPassionSession session=new CoderzPassionSession(MainActivity.this);
        name=(EditText)findViewById(R.id.username);
        email=(EditText)findViewById(R.id.email);
        password=(EditText)findViewById(R.id.password);
        signup=(Button)findViewById(R.id.signup);
        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username=name.getText().toString().trim();
                String userpassword=password.getText().toString().trim();
                String useremail=email.getText().toString().trim();
                if(username.isEmpty() || userpassword.isEmpty() ||useremail.isEmpty())
                {
                    Toast.makeText(MainActivity.this,"Please Fill all details",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    session.storeUser(username,userpassword,useremail);
                    Intent in=new Intent(MainActivity.this,LoginActivity.class);
                    startActivity(in);
                    finish();
                    Toast.makeText(MainActivity.this,"Successfully Registered please Sign in",Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

7. Now I will create  a layout for LoginActivity.java to allow user to log in and  getting values of user and password from shared preferences and setting them to username and password.

login.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"
    android:layout_margin="20dp">

    <TextView
        android:text="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/loginusername"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text="Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/loginpassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Log In"/>

</LinearLayout>

8. Now create LoginActivity.java to implement the functionality

LoginActivity.java

package com.coderzpassion.usersessionsample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by coderzpassion on 03/03/16.
 */
public class LoginActivity extends AppCompatActivity {

    EditText loginname,loginpassword;
    Button login;
    CoderzPassionSession session;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        session=new CoderzPassionSession(LoginActivity.this);
        loginname=(EditText)findViewById(R.id.loginusername);
        loginpassword=(EditText)findViewById(R.id.loginpassword);
        login=(Button)findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=loginname.getText().toString().trim();
                String pass=loginpassword.getText().toString().trim();
                if(name.isEmpty()||pass.isEmpty())
                {
                    Toast.makeText(LoginActivity.this, "Please Fill the details", Toast.LENGTH_SHORT).show();
                }
                else
                {
                 invalidateUser(name,pass);
                }
            }
        });
        setValuesFromSignUp();

    }
    public void setValuesFromSignUp()
    {
        loginname.setText(session.getUserName().equalsIgnoreCase("")?"":session.getUserName());
        loginpassword.setText(session.getUserPassword().equalsIgnoreCase("")?"":session.getUserPassword());
    }
    public void invalidateUser(String name,String pass)
    {
        if(name.equalsIgnoreCase(session.getUserName()) && pass.equalsIgnoreCase(session.getUserPassword()))
        {
            session.loginUser(name,pass,true);
            Intent in=new Intent(LoginActivity.this,HomeActivity.class);
            startActivity(in);
            finish();

        }
        else
        {
            Toast.makeText(LoginActivity.this, "Wrong Username or Password! Try again", Toast.LENGTH_SHORT).show();
        }
    }
}

9. Now create a layout for HomeActivity.java containing an option for logout.

home.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"
    android:layout_margin="20dp"
    >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/logout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Log Out"/>

</LinearLayout>

10. Now create the HomeActivity.java to implement the functionality for log out .

HomeActivity.java

package com.coderzpassion.usersessionsample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by coderzpassion on 03/03/16.
 */
public class HomeActivity extends AppCompatActivity {

    TextView username;
    Button logoutuser;
    CoderzPassionSession session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        session=new CoderzPassionSession(HomeActivity.this);
        username=(TextView)findViewById(R.id.name);
        logoutuser=(Button)findViewById(R.id.logout);
        username.setText("Welcome "+session.getUserName());
        logoutuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (session.isUserLogedIn())
                    session.logOutUser();
                Intent in=new Intent(HomeActivity.this,LoginActivity.class);
                startActivity(in);
                finish();
            }
        });


    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.usersessionsample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".HomeActivity"/>
        <activity android:name=".LoginActivity"/>
    </application>

</manifest>

Output

androidcreatingusersessionusingsharedpreferences     androidhowtocreatesessionusingsharedpreferences       androidworkingwithsharedpreferences