Skip to content

ParallelCodes

  • AngularJS
  • Android
    • Android-Creating Notepad
    • Android Widgets Tutorial
    • Android Send SMS Programmatically with Permissions
    • Making Phone Calls in Android
    • Android JSON Parsing
    • Upload Files from Android to PC Programmatically
    • Android Interview Ques & Ans
  • ASP.NET
  • MVC
  • Xamarin
  • C#
  • WPF
  • CSS Templates

ParallelCodes

  • AngularJS
  • Android
    • Android-Creating Notepad
    • Android Widgets Tutorial
    • Android Send SMS Programmatically with Permissions
    • Making Phone Calls in Android
    • Android JSON Parsing
    • Upload Files from Android to PC Programmatically
    • Android Interview Ques & Ans
  • ASP.NET
  • MVC
  • Xamarin
  • C#
  • WPF
  • CSS Templates

Android One Time Login using SharedPreferences

  • by ASH
  • April 16, 2020
Android login screen shared preferences
Post Views: 6,459

In this post we will learn how we can use Android SharedPreferences and maintain user login session. This will help us to take user directly to our app’s Homepage or Dashboard page skipping the Login process. This can be also termed as ‘One-Time Login process’. 

DOWNLOAD SOURCE CODE.

So let’s begin.

In your android app, create a new layout page with name login.xml inside (res>layout folder) and edit it as below:

res > layout > login.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:padding="10dp">

        <EditText
            android:id="@+id/edtUserid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@android:drawable/editbox_background_normal"
            android:hint="Enter UserId"
            android:padding="12dp" />

        <EditText
            android:id="@+id/edtPassword"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:background="@android:drawable/editbox_background_normal"
            android:hint="Enter your Password"
            android:inputType="textPassword"
            android:padding="12dp" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="wrap_content"
            android:layout_height="85px"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:background="#1976D2"
            android:text="LOGIN"
            android:textColor="#fff" />

        <TextView
            android:id="@+id/txtInfo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

    </LinearLayout>

</RelativeLayout>

This will be our Login screen.

Android login screen shared preferences

Android login screen shared preferences

Now create or edit your activity_main.xml file as below

res > layout > activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/txtInfo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textSize="25sp" />

        <Button
            android:id="@+id/btnLogOut"
            android:layout_width="wrap_content"
            android:layout_height="85px"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:background="#D32F2F"
            android:text="LOGOUT"
            android:textColor="#fff" />


    </LinearLayout>

</RelativeLayout>

This page will work as our Homepage or dashboard. This will contain only a simple label and an android button to show who is logged-in currently inside the app and logout button.

Android Home screen - Shared preferences login example

Android Home screen – Shared preferences login example

Now we will create Logout and Login process.

Create a new Activity file with name Login.java and edit it as below:

Login.java:

package com.app.loginsession;

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.EditText;
import android.widget.TextView;

public class Login extends AppCompatActivity {
    SharedPreferences shp;
    SharedPreferences.Editor shpEditor;
    EditText edtUserId, edtPassword;
    Button btnLogin;
    TextView txtInfo;

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

        edtUserId = findViewById(R.id.edtUserid);
        edtPassword = findViewById(R.id.edtPassword);
        edtUserId.setText("");
        edtPassword.setText("");
        btnLogin = findViewById(R.id.btnLogin);
        txtInfo = findViewById(R.id.txtInfo);
        shp = getSharedPreferences("myPreferences", MODE_PRIVATE);
        CheckLogin();

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edtUserId.getText().toString().equals("") || edtPassword.getText().toString().equals(""))
                    txtInfo.setText("Please insert userid and password");
                else
                    DoLogin(edtUserId.getText().toString(), edtPassword.getText().toString());
            }
        });
    }

    public void CheckLogin() {
        if (shp == null)
            shp = getSharedPreferences("myPreferences", MODE_PRIVATE);

        String userName = shp.getString("name", "");

        if (userName != null && !userName.equals("")) {
            Intent i = new Intent(Login.this, MainActivity.class);
            startActivity(i);
            finish();
        }
    }

    public void DoLogin(String userid, String password) {
        try {
            if (password.equals("Android3am")) {
                if (shp == null)
                    shp = getSharedPreferences("myPreferences", MODE_PRIVATE);

                shpEditor = shp.edit();
                shpEditor.putString("name", userid);
                shpEditor.commit();

                Intent i = new Intent(Login.this, MainActivity.class);
                startActivity(i);
                finish();
            } else
                txtInfo.setText("Invalid Credentails");
        } catch (Exception ex) {
            txtInfo.setText(ex.getMessage().toString());
        }
    }

}

The DoLogin method will perform login activity. If the specified password is matched, it will take user to next page and stored the username in Android SharedPreferences object.

We are also call CheckLogin() method on loading the activity to check whether a user is already logged-in from android sharedpreferences object, if so, we will directly open MainActivity.java page.

MainActivity.java:

package com.app.loginsession;

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

public class MainActivity extends AppCompatActivity {

    TextView txtInfo;
    Button btnLogOut;

    SharedPreferences shp;
    SharedPreferences.Editor shpEditor;

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

        txtInfo = findViewById(R.id.txtInfo);
        btnLogOut = findViewById(R.id.btnLogOut);

        shp = getSharedPreferences("myPreferences", MODE_PRIVATE);
        CheckLogin();

        btnLogOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logout();
            }
        });
    }

    public void CheckLogin() {
        if (shp == null)
            shp = getSharedPreferences("myPreferences", MODE_PRIVATE);


        String userName = shp.getString("name", "");

        if (userName != null && !userName.equals("")) {
            txtInfo.setText("Welcome " + userName);

        } else
        {
            Intent i = new Intent(MainActivity.this, Login.class);
            startActivity(i);
            finish();
        }
    }


    public void Logout() {
        try {
            if (shp == null)
                shp = getSharedPreferences("myPreferences", MODE_PRIVATE);

            shpEditor = shp.edit();
            shpEditor.putString("name", "");
            shpEditor.commit();

            Intent i = new Intent(MainActivity.this, Login.class);
            startActivity(i);
            finish();

        } catch (Exception ex) {
            Toast.makeText(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
        }
    }
}

This class will act as homepage or dashboard for our app. It will first check if any value exists in sharedpreferences or not, if not it will show Login screen. This a dumb logic for this app, because we are already checking it from Login page. But this method or check will be useful when you are directly calling MainActivity and not Login.java class.

DOWNLOAD SOURCE CODE.

Also edit this files:

res > values > strings.xml:

<resources>
    <string name="app_name">Login Session</string>
    <string name="user_login">User Login</string>
    <string name="user_home">Home</string>
</resources>

AndrodManifest.xml:

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

    <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=".Login"
            android:screenOrientation="portrait"
            android:label="@string/user_login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:label="@string/user_home"/>
    </application>

</manifest>

DOWNLOAD SOURCE CODE.


Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Skype (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to print (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to email a link to a friend (Opens in new window)

Related

Tags:ANDROIDandroid shared preferencesloginlogin process

Get all the latest updates for free on Facebook

Get all the latest updates for free on Facebook
 

ANDROID
  • Android – How to read Text File from Storage
  • Android Create SQLite database and Adding Data
  • Android Import Excel Sheet in SQLite Database
  • Android Import CSV file to SQLite Database
  • Android Build AAPT error: style attribute ‘attr/colorPrimary’ not found
  • Android One Time Login using SharedPreferences
  • Android Bind Expandable Listview from MS SQL Database
  • Android – How to create Expandable ListView
  • Android MS SQL Database – Create Login App
  • Android – Create Custom SnackBar with Images
  • Android Tutorial – How to use SnackBar
  • Connect Android to MS SQL Database.
  • Android Exoplayer – Play Videos from raw folder
  • Android – Load Imageview from URL in Android
  • How to create Navigation drawer in Android
  • Android How to play videos from Storage and Filepath
  • Android How to play videos using VideoView
  • Android Exoplayer – How to Play Videos Tutorial
  • How to use Android SharedPreferences – Example
  • Android Firebase How to Upload and Retrieve Images
  • How to create Android Splash Screen Animated
  • How to create Gradient Android Buttons Different Designs
  • How to bind Android Gridview from ArrayAdapter List
  • Android How to Scroll ListView Horizontally and Vertically
  • Android Google Map Add AutoComplete Place search

Neve | Powered by WordPress