Android Login And Register Using Volley PHP MySQL and Session Management

By Android Login And Register Using Volley PHP MySQL  and Session Management

Welcome to this Android tutorial. In this tutorial, I will show you how to create a login and register application in Android. This is vital in every application where the user is required to create an account and login to the app. We will store our data in MySQL database. To interact with the database, we will use a server-side language called PHP. 

I hope you have XAMPP installed on your laptop to run PHP scripts. If not, please google how to install and use XAMPP. You will get XAMPP from Apachefriends.org

Once your server is up and running, we will now create a simple PHP API to handle data from our Login and Registration Android App. Data transmission will be done in JSON format using volley Android. Volley is an HTTP library that makes networking for Android apps easier and faster.

Without much further ado, let’s start coding the login and register app.

Database Setup

First things first, let's create our database schema. Create a database with the name login_register. Then create a table with name users.

The following is the structure of the table:

CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`firtsname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`username` VARCHAR(50) NULL DEFAULT NULL,
`email` VARCHAR(50) NULL DEFAULT NULL,
`password` VARCHAR(50) NULL DEFAULT NULL,
`datetime` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE INDEX `username` (`username`),
UNIQUE INDEX `email` (`email`)
);

The above code creates a table called users. The first column is the primary key and will increment automatically. Then we have firstname and lastname columns to store the name is the user. We have a unique username column, and this means that two users cannot have the same username in our table. We also have an email column, which is also unique, and we shall store users' emails so that we can send emails to them. Then we have a password column, which will be hashed using the MD5() algorithm.

PHP scripts

We need PHP scripts to handle login and registration from Android app. We now create three scripts to handle this.

First script: Database Connection

Open your favorite IDE and create a PHP project and then create a file called db.php.

We shall open a connection to our database using PHP PDO. For installation, details read PHP PDO.

Paste lines of code into db.php file to establish database connection.

<?php
$host = "localhost";
$dbname = 'login_register';
$user = 'root';
$password = '';
$pdo = new PDO(
        'mysql:host=' . $host . ';dbname=' . $dbname, $user, $password
);

To connect to MySQL database, we need the host/location, database name, user and password.

Second Script: Registration

In this step, we will use the first script to connect to the database and insert user details there. Create a file called regieter.php to handle user registration.

We shall pick user details using PHP global variable, i.e. $_POST. The following is the code to pick data that the user will post.

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['password1'];

We shall check if all the required fields are given and tell the user to give all information if some was left out. The following code checks if all fields are provided.

if (empty($firstname) || empty($lastname) || empty($username) || empty($email) || empty($password)) {
    $response['success'] = "0";
    $response['message'] = "Some fields are empty. Please try again!";
    echo json_encode($response);
    die;
}

We shall then check if the user has confirmed the password and they match. This ensures the user will remember the provided password in future.

if ($password !== $password1) {
    $response['success'] = "0";
    $response['message'] = "Password mistmatch. Please try again!";
    echo json_encode($response);
    die();
}

We shall then check if the given email is a valid email address using the following code:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $response['success'] = "0";
    $response['message'] = "Invalid email. Please try again!";
    echo json_encode($response);
    die();
}

We shall then check if the provided username and email does not exist in the database. We are ensuring that one username and email address is attached to only one user. The following code checks that:

if (checkEmail($email)) {
    $response['success'] = "0";
    $response['message'] = "That email is registered. Please try again!";
    echo json_encode($response);
    die();
}

//Check if email exists
if (checkUsername($username)) {
    $response['success'] = "0";
    $response['message'] = "That username is registered. Please try again!";
    echo json_encode($response);
    die();
}

After we have validated the data we now proceeding with registration. We shall call registerUser() method that inserts the details in the database.

The whole code for register.php file is:

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['password1'];
$response = array();
//Check if all fieds are given
if (empty($firstname) || empty($lastname) || empty($username) || empty($email) || empty($password)) {
    $response['success'] = "0";
    $response['message'] = "Some fields are empty. Please try again!";
    echo json_encode($response);
    die;
}
//Check if password match
if ($password !== $password1) {
    $response['success'] = "0";
    $response['message'] = "Password mistmatch. Please try again!";
    echo json_encode($response);
    die();
}
//Check if email is a valid one
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $response['success'] = "0";
    $response['message'] = "Invalid email. Please try again!";
    echo json_encode($response);
    die();
}
//Check if email exists
if (checkEmail($email)) {
    $response['success'] = "0";
    $response['message'] = "That email is registered. Please try again!";
    echo json_encode($response);
    die();
}

//Check if email exists
if (checkUsername($username)) {
    $response['success'] = "0";
    $response['message'] = "That username is registered. Please try again!";
    echo json_encode($response);
    die();
}
$userdetails = array(
    'firstname' => $firstname,
    'lastname' => $lastname,
    'username' => $username,
    'email' => $email,
    'password' => md5($password),
);
//Insert the user into the database
if (registerUser($userdetails)) {
    $response['success'] = "1";
    $response['message'] = "User registered successfully!";
    echo json_encode($response);
} else {
    $response['success'] = "0";
    $response['message'] = "User registration failed. Please try again!";
    echo json_encode($response);
}
function registerUser($userdetails) {
    require './db.php';
    $query = "INSERT INTO users (firstname, lastname, username, email, password) VALUES "
            . "(:firstname, :lastname, :username, :email, :password)";
    $stmt = $pdo->prepare($query);
    return $stmt->execute($userdetails);
}
function checkEmail($value) {
    require './db.php';
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? ");
    $stmt->execute([$value]);
    $array = $stmt->fetch(PDO::FETCH_ASSOC);
    $stmt = null;
    return !empty($array);
}
function checkUsername($value) {
    require './db.php';
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? ");
    $stmt->execute([$value]);
    $array = $stmt->fetch(PDO::FETCH_ASSOC);
    $stmt = null;
    return !empty($array);
}

Third Script: Login

After a user has been registered in the database, we can now try to log in. Now create a new file called login.php. We shall use the same database connection script, db.php, to read users from the database, and authenticate them. 

We shall pick user data using $_POST variable and try to log in.

Paste the following code into login.php file. 

<?php
$user = $_POST['user'];
$password = $_POST['password'];
$response = array();
//Check if all fieds are given
if (empty($user) || empty($password)) {
    $response['success'] = "0";
    $response['message'] = "Some fields are empty. Please try again!";
    echo json_encode($response);
    die;
}
$userdetails = array(
    'user' => $user,
    'password' => md5($password)
);
//Insert the user into the database
$success = loginUser($userdetails);
if (!empty($success)) {
    $response['success'] = "1";
    $response['message'] = "Login successfully!";
    $response['details'] = $success;
    echo json_encode($response);
} else {
    $response['success'] = "0";
    $response['message'] = "Login failed. Please try again!";
    echo json_encode($response);
}
function loginUser($userdetails) {
    require './db.php';
    $array = array();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE (email = :user OR username = :user ) AND password = :password");
    $stmt->execute($userdetails);
    $array = $stmt->fetch(PDO::FETCH_ASSOC);
    $stmt = null;
    return $array;
}

So our PHP project has three files, namely: db.php, register.php, and login.php. Ensure all the files are in the same directory.

Android Login Register Project

Now let us follow all steps on the Android Studio to create a login and register app.

1. Now create a new project in Android Studio. Go to File ⇒ New Project. When it prompts you to select the default activity, select Empty Activity, and proceed.

2. Open build.gradle in (Module:app) and add Volley dependencies like this.

dependencies {
    …..
    implementation 'com.android.volley:volley:1.1.1'
}

The above line allows as to use volley library to send http calls to our PHP login and register API

3. Open AndroidManifest.xml and add permissions for the INTERNET like this.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.login_register">
    <uses-permission android:name="android.permission.INTERNET" />
    …….
</manifest>

The above permission allows us to access internet.

4. Next, we shall create a class to store user details in shared preferences. This class will help us maintain the login session. Many available login and register tutorials do not show how to manage the login session, so I found it important to show you in this article.

A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. So in our case, we shall store key-value pairs for user information.

So create a class called SharedPrefrencesHelper.java and paste the following code:

package com.example.login_register;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPrefrencesHelper {
    private SharedPreferences sharedPreferences;
    private Context context;
    private String firstname = "firstname", lastname = "lastname", username = "username", email = "email";
    public SharedPrefrencesHelper(Context context) {
        this.sharedPreferences = context.getSharedPreferences("login_session",
                Context.MODE_PRIVATE);
        this.context = context;
    }
    public String getFirstname() {
        return sharedPreferences.getString(firstname, "");
    }
    public String getLastname() {
        return sharedPreferences.getString(lastname, "");
    }
    public String getUsername() {
        return sharedPreferences.getString(username, "");
    }
    public String getEmail() {
        return sharedPreferences.getString(email, "");
    }
    public void setFirstname(String firstname) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(this.firstname, firstname);
        edit.commit();
    }
    public void setLastname(String lastname) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(this.lastname, lastname);
        edit.commit();
    }
    public void setUsername(String username) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(this.username, username);
        edit.commit();
    }
    public void setEmail(String email) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(this.email, email);
        edit.commit();
    }
}

The above class has four fields to store the first name, last name, username, and email of the user. After a successful login, user data will be retrieved from the database by PHP code, and this class will store this data using the appropriate setter methods. When the user logs out, we shall simply remove data from shared preferences. We shall use getter methods to retrieve information from shared preferences.

Android Main Activity

Let's now create mainActivity.java and activity_main.xml files. When the user launches the app, it will first check if the user is logged in by reading information from the shared preferences. If there is data, then the user is logged, and if there is no data, then the user is not logged and must be directed to the login activity.

Paste the following code in activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_margin="30dp"
        android:scrollbars="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:gravity="center"
                android:text="Welcome to something Big!!"
                android:textSize="30dp"
                android:textStyle="bold"/>
            <TextView
                android:id="@+id/firstname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:text="First Name"
                android:textSize="20dp" />
            <TextView
                android:id="@+id/lastname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:text="Last Name"
                android:textSize="20dp" />
            <TextView
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:text="Username"
                android:textSize="20dp" />
            <TextView
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:text="Email"
                android:textSize="20dp" />

        </LinearLayout>
    </ScrollView>
    <Button
        android:id="@+id/logoutBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="Logout"
        android:layout_margin="30dp"
        android:textColor="#FFF"
        android:textSize="20dp"
        />
</LinearLayout>

Paste the following code in MainActivity.java:

package com.example.login_register;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    private SharedPrefrencesHelper sharedPrefrencesHelper;
    TextView firstname, lastname, usernamee, email;
    Button logoutBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sharedPrefrencesHelper = new SharedPrefrencesHelper(this);
        String username = sharedPrefrencesHelper.getUsername();
        if (username == null || username.isEmpty()) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        firstname = findViewById(R.id.firstname);
        lastname = findViewById(R.id.lastname);
        usernamee = findViewById(R.id.username);
        email = findViewById(R.id.email);
        logoutBtn = findViewById(R.id.logoutBtn);
        firstname.setText(sharedPrefrencesHelper.getFirstname());
        lastname.setText(sharedPrefrencesHelper.getLastname());
        usernamee.setText(sharedPrefrencesHelper.getUsername());
        email.setText(sharedPrefrencesHelper.getEmail());
        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharedPrefrencesHelper.setFirstname(null);
                sharedPrefrencesHelper.setLastname(null);
                sharedPrefrencesHelper.setUsername(null);
                sharedPrefrencesHelper.setEmail(null);
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
            }
        });
    }
}

The following code checks whether the user is logged and redirects to login activity if not logged in.

String username = sharedPrefrencesHelper.getUsername();
if (username == null || username.isEmpty()) {
    startActivity(new Intent(this, LoginActivity.class));
    finish();
}

If the user is logged in we read his/her data from the shared preferences and display them on the app.

Android Register Code

Now we shall create code to handle user registration. We shall create a java class and XML class for this purpose.

Paste the following code in activity_register.xml:

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    tools:context=".LoginActivity">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="30dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="First Name"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/firstName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Fisrt Name"
                android:inputType="text"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Last Name"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/lastName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Last Name"
                android:inputType="text"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Username"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Username"
                android:inputType="text"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Email"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Email"
                android:inputType="textEmailAddress"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Password"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Password"
                android:inputType="textPassword"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Confirm Password"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/password1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Confirm Password"
                android:inputType="textPassword"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <Button
                android:id="@+id/registerBtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                android:layout_marginBottom="20dp"
                android:text="Register"
                android:textColor="#FFF"
                android:textSize="20dp" />
            <TextView
                android:id="@+id/loginTV"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Have Account? Login Here"
                android:gravity="center"
                android:paddingVertical="10dp"
                android:textSize="20dp"
                android:layout_marginBottom="50dp">
            </TextView>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Paste the following code in RegisterActivity.java:

package com.example.login_register;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
    TextView loginTV;
    EditText fisrtName, lastName, username, email, password, password1;
    Button registerBtn;
    private RequestQueue rQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        loginTV = findViewById(R.id.loginTV);
        fisrtName = findViewById(R.id.firstName);
        lastName = findViewById(R.id.lastName);
        username = findViewById(R.id.username);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        password1 = findViewById(R.id.password1);
        registerBtn = findViewById(R.id.registerBtn);

        loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(), LoginActivity.class));
            }
        });
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                registerAction();
            }
        });
    }

    private void registerAction() {
        final String fname = fisrtName.getText().toString();
        final String lname = lastName.getText().toString();
        final String uname = username.getText().toString();
        final String mail = email.getText().toString();
        final String pswd = password.getText().toString();
        final String pswd1 = password1.getText().toString();
        if (fname.isEmpty()) {
            fisrtName.setError("First name is required");
            fisrtName.requestFocus();
            return;
        }
        if (lname.isEmpty()) {
            lastName.setError("Last name is required");
            lastName.requestFocus();
            return;
        }
        if (uname.isEmpty()) {
            username.setError("Username is required");
            username.requestFocus();
            return;
        }
        if (mail.isEmpty()) {
            email.setError("Email is required");
            email.requestFocus();
            return;
        }
        if (pswd.isEmpty()) {
            password.setError("Password is required");
            password.requestFocus();
            return;
        }
        if (!pswd.equals(pswd1)) {
            password1.setError("Password mismatch");
            password1.requestFocus();
            return;
        }

        StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.url) + "register.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        rQueue.getCache().clear();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("success").equals("1")) {
                                Toast.makeText(RegisterActivity.this, "Registered Successfully! Now Login", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                finish();
                            } else {
                                Toast.makeText(RegisterActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(RegisterActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("firstname", fname);
                params.put("lastname", lname);
                params.put("username", uname);
                params.put("email", mail);
                params.put("password", pswd);
                params.put("password1", pswd1);
                return params;
            }
        };
        rQueue = Volley.newRequestQueue(RegisterActivity.this);
        rQueue.add(stringRequest);
    }
}

Let’s explain the above lines step by step.

In strings.xml, we have defined a parameter called URL, which holds the base URL of our PHP project. When using the volley library, we send a string request. This request contains method type, ie, either GET or POST, URL (endpoint or of PHP login and register API), and data that will be processed by PHP.

The user will first fill all the provided fields and click the register button. When the button is clicked, registerAction() method is executed. Here we check if all fields are filled before posting the values to PHP. This is known as client-side validation.

If all fields are filled, we use StringRequest class to send the data to PHP. When data is sent through HTTP call using volley and JSON response is received, the compiler executes onResponse() method. This is where we get the response and read the data returned from our PHP register code. Here we run a very important line, rQueue.getCache().clear(); It will prevent volley from making HTTP calls more than one time. So ensure you have this line here.

If the client(Android) and server (PHP) communicate without errors, we expect JSON response with a key (success) with value "0" or "1". If the value of success is "1," then the registration was successful, and we direct the user to login activity. If the value is "0", it means there was an error, and we display the message to the user.

If an error occurs during the communication, the compiler runs onError() method and it tells us the kind of the error.

getParams() method prepares parameters for HTTP call. We create a HashMap of key-value pairs.

Android Login Code

So after registration or log out it is time to log into the just created application. Create two files LoginActivity.java and activity_login.xml.

Paste the following code in activity_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    tools:context=".LoginActivity">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="30dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Username or Email"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/user"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Username or Email"
                android:inputType="textAutoComplete"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Password"
                android:textSize="20dp">
            </TextView>
            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="30dp"
                android:hint="Password"
                android:inputType="textPassword"
                android:singleLine="true"
                android:textSize="20dp">
            </EditText>
            <Button
                android:id="@+id/loginBtn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                android:layout_marginBottom="30dp"
                android:text="Login"
                android:textColor="#FFF"
                android:textSize="20dp" />
            <TextView
                android:id="@+id/registerTV"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="No Accont? Register Here"
                android:gravity="center"
                android:paddingVertical="10dp"
                android:textSize="20dp">
            </TextView>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Paste the following code in LoginActivity.java:

package com.example.login_register;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
    TextView registerTV;
    EditText user, password;
    Button loginBtn;
    private RequestQueue rQueue;
    private SharedPrefrencesHelper sharedPrefrencesHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        registerTV = findViewById(R.id.registerTV);
        user = findViewById(R.id.user);
        password = findViewById(R.id.password);
        loginBtn = findViewById(R.id.loginBtn);
        sharedPrefrencesHelper = new SharedPrefrencesHelper(this);
        registerTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(), RegisterActivity.class));
            }
        });
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginAction();
            }
        });
    }
    private void loginAction() {
        final String userr = user.getText().toString();
        final String pswd = password.getText().toString();
        if (userr.isEmpty()) {
            user.setError("Username or Email is required");
            user.requestFocus();
            return;
        }
        if (pswd.isEmpty()) {
            password.setError("Password is required");
            password.requestFocus();
            return;
        }

        StringRequest stringRequest = new StringRequest(Request.Method.POST, getResources().getString(R.string.url) + "login.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        rQueue.getCache().clear();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("success").equals("1")) {
                                JSONObject jsonObject1 = jsonObject.getJSONObject("details");
                                sharedPrefrencesHelper.setFirstname(jsonObject1.getString("firstname"));
                                sharedPrefrencesHelper.setLastname(jsonObject1.getString("lastname"));
                                sharedPrefrencesHelper.setUsername(jsonObject1.getString("username"));
                                sharedPrefrencesHelper.setEmail(jsonObject1.getString("email"));

                                Toast.makeText(LoginActivity.this, "Login Successfully! ", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getBaseContext(), MainActivity.class));
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("user", userr);
                params.put("password", pswd);
                return params;
            }
        };
        rQueue = Volley.newRequestQueue(LoginActivity.this);
        rQueue.add(stringRequest);
    }
}

The code for this class is more similar to register one.

We have two fields, one for the username or email and another one for password. Then we have a button and a link for new users to register into the system.

When a user clicks the button, the app checks whether the username or email and password are filled. Then make HTTP call using volley to verify and authenticate this user.

When the HTTP call is made, and the JSON response is returned, the onRespsonse() method is executed. Kindly don't forget to clear the cache after the response by using rQueue.getCache().clear(); On successful response, we expect the JSON object to have a key (success) with either "0" or "1". If the value is "0," then the user gave wrong details. He must try to login with new credentials. 

If the value is "1", the details were corrected, and the login was a success, so the server returned user's details as they are in the database. Here we read these values and store them in shared preferences using the following lines of code.

JSONObject jsonObject1 = jsonObject.getJSONObject("details");
sharedPrefrencesHelper.setFirstname(jsonObject1.getString("firstname"));
sharedPrefrencesHelper.setLastname(jsonObject1.getString("lastname"));
sharedPrefrencesHelper.setUsername(jsonObject1.getString("username"));
sharedPrefrencesHelper.setEmail(jsonObject1.getString("email"));

Then we redirect the user to the main activity. In the main activity the user will see his/her details as stored in the shared preferences.

If the user clicks the logout button, this action will set values of shared preference to null and redirect the user to login activity.

logoutBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        sharedPrefrencesHelper.setFirstname(null);
        sharedPrefrencesHelper.setLastname(null);
        sharedPrefrencesHelper.setUsername(null);
        sharedPrefrencesHelper.setEmail(null);
        startActivity(new Intent(MainActivity.this, LoginActivity.class));
        finish();
    }
});

Output

These are the screenshots form main activity, login and register.


Conclusion

That is how to register and log into Android using PHP and MySQL using the Volley library. 

You can get the complete code for Android Upload Image to Server Using Retrofit from my GitHub repository. You may also make changes to the code and use it in your projects.

Thank you for reading this article. Please vote below and share it with your friends and fellow android developers.

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.