Android Login and Registration Using Sharedpreferences

By | May 28, 2022

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

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.

Popular:   Infor Hcm Workforce Management Etm Login

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.

Android Login and Registration Using Sharedpreferences

Source: https://parallelcodes.com/android-one-time-login-using-sharedpreferences/

Popular:   Https Www Allstardriveredonline Com Ohio Html