In this tutorial I am going to explain how to build complete login and registration system in android using PHP, MySQL and SQLite. Also this tutorial covers how to build simple API using PHP and MySQL.

Download Android Code Download PHP Code

VIDEO DEMO

Below are the final outputs of this project.

Android Login And Registration Using PHP MySQL and SQLite

Prerequisites

Android working with Volley Library – Used to make HTTP calls. Make sure you went through the this article if you are very beginner.

What is API ?

API is Stands for Application Programming Interface. To interact with MySQL database we need to build a REST API first. REST Api job is to get the request from client, interact with database and finally give the response back to client. So we’ll create a simple PHP, MySQL API first. Our API do’s below jobs.

  • Accepts requests in GET/POST methods.
  • Interact with database by inserting / fetching data.
  • Finally will give response back in JSON format.

1. Downloading & Installing XAMPP

Download & Install XAMPP server from https://www.apachefriends.org/download.html. Once installed, launch the XAMPP control panel and Start Apache and MySQL.

You can test your server by opening the address http://localhost/ in your browser. Also you can check phpmyadmin by opening http://localhost/phpmyadmin

2. Creating MySQL Database and Tables

Open phpmyadmin and execute below queries to create necessary database and table. Here we are creating only one table users to store users login information. if you have problem in Executing this SQL query go and watch first above video.

create database android_api /** Creating Database **/

   use android_api /** Selecting Database **/

   create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
   ); /** Creating Users Table **/

3. Creating PHP Project

Goto the location where XAMPP installed and open htdocs folder. The default installation location of XAMPP would be C:/XAMPP. Below is the final PHP project structure we are going to create in this article.

1. Go into htdocs folder and create a folder named android_login_api. This will be the root directory of our project.

2. In android_login_api, create another directory named include. In this folder, we keep all the helper classes.

3. Now inside include, create a php file named Config.php and add below content. Replace the DB_USER and DB_PASSWORD values with your’s.

Config.php

<?php

/**
 * Database config variables
 */
   define("DB_HOST", "localhost");
   define("DB_USER", "root");
   define("DB_PASSWORD", "");
   define("DB_DATABASE", "android_api");

?>

4. Create a class named DB_Connect.php in include and paste below code. In this class we handle opening and closing of database connection.

DB_Connect.php

<?php

class DB_Connect {
   private $conn;

   // Connecting to database
   public function connect() {
      require_once 'include/Config.php';

      // Connecting to mysql database
      $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

      // return database handler
      return $this->conn;

   }
}

?>

5. Create DB_Functions.php inside include with below content. This file contains functions to store user in database, get user from database. You can also add methods like update user, delete user.

unique id – I am generating unique user id in php using uniqid(”, true) function. Sample user id will be like 4f074eca601fb8.88015924
 
Encrypted Password – The passwords are stored using base64_encode method. Each password needs two columns to store it in database. One is to store encrypted password and other is to store salt used to encrypt the password.

DB_Functions.php

<?php

class DB_Functions {

   private $conn;

   // constructor
   function __construct() {
      require_once 'DB_Connect.php';
      // connecting to database
      $db = new Db_Connect();
      $this->conn = $db->connect();
   }

   // destructor
   function __destruct() {

   }

   /**
    * Storing new user
    * returns user details
    */
   public function storeUser($name, $email, $password) {
      $uuid = uniqid('', true);
      $hash = $this->hashSSHA($password);
      $encrypted_password = $hash["encrypted"]; // encrypted password
      $salt = $hash["salt"]; // salt

      $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
      $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
      $result = $stmt->execute();
      $stmt->close();

      // check for successful store
      if ($result) {
         $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
         $stmt->bind_param("s", $email);
         $stmt->execute();
         $user = $stmt->get_result()->fetch_assoc();
         $stmt->close();

         return $user;
      } else {
         return false;
      }
   }

   /**
    * Get user by email and password
    */
   public function getUserByEmailAndPassword($email, $password) {

      $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

      $stmt->bind_param("s", $email);

      if ($stmt->execute()) {
         $user = $stmt->get_result()->fetch_assoc();
         $stmt->close();

         // verifying user password
         $salt = $user['salt'];
         $encrypted_password = $user['encrypted_password'];
         $hash = $this->checkhashSSHA($salt, $password);
         // check for password equality
         if ($encrypted_password == $hash) {
            // user authentication details are correct
            return $user;
         }
      } else {
         return NULL;
      }
   }

   /**
    * Check user is existed or not
    */
   public function isUserExisted($email) {
      $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

      $stmt->bind_param("s", $email);

      $stmt->execute();

      $stmt->store_result();

      if ($stmt->num_rows > 0) {
         // user existed 
         $stmt->close();
         return true;
      } else {
         // user not existed
         $stmt->close();
         return false;
      }
   }

   /**
    * Encrypting password
    * @param password
    * returns salt and encrypted password
    */
   public function hashSSHA($password) {

      $salt = sha1(rand());
      $salt = substr($salt, 0, 10);
      $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
      $hash = array("salt" => $salt, "encrypted" => $encrypted);
      return $hash;
   }

   /**
    * Decrypting password
    * @param salt, password
    * returns hash string
    */
   public function checkhashSSHA($salt, $password) {

      $hash = base64_encode(sha1($password . $salt, true) . $salt);

      return $hash;
   }

}

?>

3.1 Registration Endpoint

Now we have all the required classes ready. Let’s start creating the endpoint for user registration. This endpoint accepts name, email and password as POST parameters and store the user in MySQL database.

6. In android_login_api root directory, create register.php and below code.

register.php

<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {

        // receiving the post params
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed with the same email
        if ($db->isUserExisted($email)) {
        // user already existed
        $response["error"] = TRUE;
        $response["error_msg"] = "User already existed with " . $email;
        echo json_encode($response);
     } else {
        // create a new user
        $user = $db->storeUser($name, $email, $password);
        if ($user) {
            // user stored successfully
            $response["error"] = FALSE;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = TRUE;
            $response["error_msg"] = "Unknown error occurred in registration!";
            echo json_encode($response);
             }
           }
        } else {
            $response["error"] = TRUE;
            $response["error_msg"] = "Required parameters (name, email or password) is missing!";
            echo json_encode($response);
        }
?>

3.2 Login Endpoint

Just like registration, we need to create another endpoint for login. This endpoint accepts email and password as POST parameters. After receiving the email and password, it checks in database for matched user. If the user is matched, it echoes the success the json response.

7. Create a php file named login.php inside android_login_api with the below content.

login.php

<?php

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['email']) && isset($_POST['password'])) {

        // receiving the post params
        $email = $_POST['email'];
        $password = $_POST['password'];

        // get the user by email and password
        $user = $db->getUserByEmailAndPassword($email, $password);

        if ($user != false) {
        // use is found
            $response["error"] = FALSE;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user is not found with the credentials
            $response["error"] = TRUE;
            $response["error_msg"] = "Login credentials are wrong. Please try again!";
            echo json_encode($response);
        }
    } else {
        // required post params is missing
        $response["error"] = TRUE;
        $response["error_msg"] = "Required parameters email or password is missing!";
        echo json_encode($response);
    }
?>

3.3 Types of JSON Responses

The following are the different types of JSON responses for registration and login endpoints.

3.3.1 Registration

URL: http://localhost/android_login_api/register.php

PARAMS: name, email, password

Registration Success Response

{
    "error": false,
    "uid": "5ea01514837f79.86513621",
    "user": {
        "name": "Yash Pawar",
        "email": "Yash@CodeDecode.in",
        "created_at": "2020-04-22 15:27:40",
        "updated_at": null
    }
}

Registration error – storing User’s Response

{
    "error": 1,
    "error_msg": "Unknown error occurred in registration!"
}

Registration error – User Already Existed Response

{
    "success": 0,
    "error": 2,
    "error_msg": "User already existed with ravi8x@androidhive.info"
}

3.3.2 Login

URL: http://localhost/android_login_api/login.php

PARAMS: email, password

Login Success Response

{
    "error": false,
    "uid": "5ea01514837f79.86513621",
        "user": {
        "name": "Yash Pawar",
        "email": "Yash@CodeDecode.in",
        "created_at": "2020-04-22 15:27:40",
        "updated_at": null
    }
}

Login error – Incorrect username / password Response

{
    "tag": "login",
    "success": 0,
    "error": 1,
    "error_msg": "Login credentials are incorrect. Please try again!"
}

Now we have completed the PHP part. Let’s start the android part.

4. Creating the Android Project

The app we’re gonna build will have three simple screens Login Screen, Registration Screen and a welcome Dashboard Screen.

1. In Android Studio, create a new project from File ⇒ New ⇒ New Project and fill all the required details.

2. Create three folders named app, activity and helper under package.

3. Open build.gradle and add volley library support under dependency.

build.gradle

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

4. Open strings.xml located under res ⇒ values and add below string values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Login and Registration Using PHP MySQL</string>
    <string name="hint_email">Email</string>
    <string name="hint_password">Password</string>
    <string name="hint_name">Fullname</string>
    <string name="btn_login">LOGIN</string>
    <string name="btn_register">REGISTER</string>
    <string name="btn_link_to_register">Not a member? Sign up now</string>
    <string name="btn_link_to_login">Already registred! Login Here</string>
    <string name="welcome">Welcome</string>
    <string name="btn_logout">LOGOUT</string>
    <string name="name">Fullname</string>
</resources>

5. Open colors.xml located under res ⇒ values and add the color values.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimaryDark">#2e3237</color>
    <color name="bg_login">#ffb74d</color>
    <color name="input_login_bg">#FFDBA6</color>
    <color name="bg_register">#2e3237</color>
    <color name="white">#ffffff</color>
    <color name="input_login">#222222</color>
    <color name="input_login_hint">#999999</color>
    <color name="input_register">#888888</color>
    <color name="input_register_bg">#3b4148</color>
    <color name="input_register_hint">#A1A1A1</color>
    <color name="btn_login">#ffb74d</color>
    <color name="btn_login_bg">#eceef1</color>
    <color name="lbl_name">#333333</color>
    <color name="btn_logout_bg">#ff6861</color>
</resources>

6. Under app package create a class named AppConfig.java and add below code. In this class we declare the login and registration URLs. While testing you need to replace the ip address with your localhost PC ip. for get your PC ip just run ipconfig command in CMD you can see IPv4 Address is this yout machine ip.

AppConfig.java

package com.codedecode.loginregister.app;

public class AppConfig {
   // Server user login url
   public static String URL_LOGIN = "http://192.162.48.248/android_login_api/login.php/";

   // Server user register url
   public static String URL_REGISTER = "http://192.162.48.248/android_login_api/register.php/";
}

7. Under app package, create a class named AppController.java. This class extends from Application which should be executed on app launch. In this class we initiate all the volley core objects.

AppController.java

package com.codedecode.loginregister.app;

import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

   public static final String TAG = AppController.class.getSimpleName();

   private RequestQueue mRequestQueue;

   private static AppController mInstance;

   @Override
   public void onCreate() {
      super.onCreate();
      mInstance = this;
   }

   public static synchronized AppController getInstance() {
      return mInstance;
   }

   public RequestQueue getRequestQueue() {
      if (mRequestQueue == null) {
         mRequestQueue = Volley.newRequestQueue(getApplicationContext());
      }

      return mRequestQueue;
   }

   public <T> void addToRequestQueue(Request<T> req, String tag) {
      req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
      getRequestQueue().add(req);
   }

   public <T> void addToRequestQueue(Request<T> req) {
      req.setTag(TAG);
      getRequestQueue().add(req);
   }

   public void cancelPendingRequests(Object tag) {
      if (mRequestQueue != null) {
         mRequestQueue.cancelAll(tag);
      }
   }
}

8. Now open AndroidManifest.xml and add INTERNET permission. Add the AppController class to <application> tag. Also add other activities (LoginActivity, RegisterActivity and MainActivity) which we are going to create shortly. I am keeping LoginActivity as launcher activity as it should be seen on app launch.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codedecode.loginregister">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".app.AppController"
        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"
        android:usesCleartextTraffic="true">
        <activity android:name=".activity.LoginActivity"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" />
    </application>

</manifest>

9. Under helper package, create a class named SessionManager.java and add below code. This class maintains session data across the app using the SharedPreferences. We store a boolean flag isLoggedIn in shared preferences to check the login status.

My previous article Android Static Login Using Shared Preferences gives you a good overview of managing the session data using SharedPreferences.

SessionManager.java

package com.codedecode.loginregister.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class SessionManager {
   // LogCat tag
   private static String TAG = SessionManager.class.getSimpleName();

   // Shared Preferences
   private SharedPreferences pref;

   private Editor editor;

   // Shared preferences file name
   private static final String PREF_NAME = "CodeDecodeLogin";
   
   private static final String KEY_IS_LOGGED_IN = "isLoggedIn";

   public SessionManager(Context context) {
      // Shared pref mode
      int PRIVATE_MODE = 0;
      pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
      editor = pref.edit();
   }

   public void setLogin(boolean isLoggedIn) {

      editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);

      // commit changes
      editor.commit();

      Log.d(TAG, "User login session modified!");
   }
   
   public boolean isLoggedIn(){
      return pref.getBoolean(KEY_IS_LOGGED_IN, false);
   }
}

10. Under helper package, create a class named SQLiteHandler.java and paste the below code. This class takes care of storing the user data in SQLite database. Whenever we needs to get the logged in user information, we fetch from SQLite instead of making request to server.

package com.codedecode.loginregister.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.HashMap;

public class SQLiteHandler extends SQLiteOpenHelper {

   private static final String TAG = SQLiteHandler.class.getSimpleName();

   // All Static variables
   // Database Version
   private static final int DATABASE_VERSION = 1;

   // Database Name
   private static final String DATABASE_NAME = "android_api";

   // Login table name
   private static final String TABLE_USER = "user";

   // Login Table Columns names
   private static final String KEY_ID = "id";
   private static final String KEY_NAME = "name";
   private static final String KEY_EMAIL = "email";
   private static final String KEY_UID = "uid";
   private static final String KEY_CREATED_AT = "created_at";

   public SQLiteHandler(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   // Creating Tables
   @Override
   public void onCreate(SQLiteDatabase db) {
      String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
      db.execSQL(CREATE_LOGIN_TABLE);

      Log.d(TAG, "Database tables created");
   }

   // Upgrading database
   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // Drop older table if existed
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

      // Create tables again
      onCreate(db);
   }

   /**
    * Storing user details in database
    * */
   public void addUser(String name, String email, String uid, String created_at) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(KEY_NAME, name); // Name
      values.put(KEY_EMAIL, email); // Email
      values.put(KEY_UID, uid); // Email
      values.put(KEY_CREATED_AT, created_at); // Created At

      // Inserting Row
      long id = db.insert(TABLE_USER, null, values);
      db.close(); // Closing database connection

      Log.d(TAG, "New user inserted into sqlite: " + id);
   }

   /**
    * Getting user data from database
    * */
   public HashMap<String, String> getUserDetails() {
      HashMap<String, String> user = new HashMap<String, String>();
      String selectQuery = "SELECT  * FROM " + TABLE_USER;

      SQLiteDatabase db = this.getReadableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);
      // Move to first row
      cursor.moveToFirst();
      if (cursor.getCount() > 0) {
         user.put("name", cursor.getString(1));
         user.put("email", cursor.getString(2));
         user.put("uid", cursor.getString(3));
         user.put("created_at", cursor.getString(4));
      }
      cursor.close();
      db.close();
      // return user
      Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

      return user;
   }

   /**
    * Re crate database Delete all tables and create them again
    * */
   public void deleteUsers() {
      SQLiteDatabase db = this.getWritableDatabase();
      // Delete All Rows
      db.delete(TABLE_USER, null, null);
      db.close();

      Log.d(TAG, "Deleted all user info from sqlite");
   }

}

4.1 Adding the Login Screen

Now we’ll implement the login module by creating the screen and adding the code to make login request to php, mysql server.

11. Create an xml file named activity_login.xml under res ⇒ layout.

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/bg_login"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_login_bg"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <EditText

            android:id="@+id/password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_login_bg"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/input_login"
            android:text="@string/btn_login"
            android:textColor="@color/btn_login" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

</LinearLayout>

12. Create an activity class named LoginActivity.java under activity package. In this class. checkLogin() – Method verifies the login details on the server by making the volley http request.

LoginActivity.java

package com.codedecode.loginregister.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.codedecode.loginregister.R;
import com.codedecode.loginregister.app.AppConfig;
import com.codedecode.loginregister.app.AppController;
import com.codedecode.loginregister.helper.SQLiteHandler;
import com.codedecode.loginregister.helper.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputEmail = findViewById(R.id.email);
        inputPassword = findViewById(R.id.password);
        Button btnLogin = findViewById(R.id.btnLogin);
        Button btnLinkToRegister = findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter Email and Password!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }
        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Now if you run the app, you should see the login screen. But login might not work as we don’t have any user information in mysql database. That can be done by adding the registration screen.

4.1 Adding the Registration Screen

13. Create an xml layout named activity_register.xml under res ⇒ layout.

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/bg_register"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="@string/hint_name"
            android:padding="10dp"
            android:singleLine="true"
            android:inputType="textCapWords"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/bg_login"
            android:text="@string/btn_register"
            android:textColor="@color/input_login" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToLoginScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_login"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

</LinearLayout>

14. Create an activity class named RegisterActivity.java under activity package.

  • registerUser() – Will store the user by passing name, email and password to PHP, MySQL server.
  • db.addUser() – Will insert the user in SQLite database once he is successfully registered.

RegisterActivity.java

package com.codedecode.loginregister.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.codedecode.loginregister.R;
import com.codedecode.loginregister.app.AppConfig;
import com.codedecode.loginregister.app.AppController;
import com.codedecode.loginregister.helper.SQLiteHandler;
import com.codedecode.loginregister.helper.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        inputFullName = findViewById(R.id.name);
        inputEmail = findViewById(R.id.email);
        inputPassword = findViewById(R.id.password);
        Button btnRegister = findViewById(R.id.btnRegister);
        Button btnLinkToLogin = findViewById(R.id.btnLinkToLoginScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        SessionManager session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(RegisterActivity.this,
                    MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                    registerUser(name, email, password);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your details!", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * Function to store user in MySQL database will post params(tag, name,
     * email, password) to register url
     * */
    private void registerUser(final String name, final String email,
                              final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Run the app and navigate to register screen by tapping on the link below login button.

android register screen layout.png

4.3 Adding the Home Screen

Until now we are done with both Login and Registration screen. Now we’ll add the Final screen (Dashboard Screen) to show the logged in User Information. This information will be fetched from SQLite database once user is logged in.

15. Create an xml file named activity_main.xml under res ⇒ layout and add below code.

activity_main.xml

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/welcome"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:textAllCaps="true"
            android:textColor="@color/lbl_name"
            android:textSize="24dp" />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13dp" />

        <Button
            android:id="@+id/btnLogout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@color/btn_logout_bg"
            android:text="@string/btn_logout"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

</RelativeLayout>

16. Open the MainActivity.java and do below changes. Here we are just fetching the logged user information from SQLite and displaying it on the screen. The logout button will logout the user by clearing the session and deleting the user from SQLite table.

MainActivity.java

package com.codedecode.loginregister.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.codedecode.loginregister.R;
import com.codedecode.loginregister.helper.SQLiteHandler;
import com.codedecode.loginregister.helper.SessionManager;
import java.util.HashMap;

public class MainActivity extends Activity {

   private SQLiteHandler db;
   private SessionManager session;

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

      TextView txtName = findViewById(R.id.name);
      TextView txtEmail = findViewById(R.id.email);
      Button btnLogout = findViewById(R.id.btnLogout);

      // SqLite database handler
      db = new SQLiteHandler(getApplicationContext());

      // session manager
      session = new SessionManager(getApplicationContext());

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

      // Fetching user details from SQLite
      HashMap<String, String> user = db.getUserDetails();

      String name = user.get("name");
      String email = user.get("email");

      // Displaying the user details on the screen
      txtName.setText(name);
      txtEmail.setText(email);

      // Logout button click event
      btnLogout.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View v) {
            logoutUser();
         }
      });
   }

   /**
    * Logging out the user. Will set isLoggedIn flag to false in shared
    * preferences Clears the user data from sqlite users table
    * */
   private void logoutUser() {
      session.setLogin(false);

      db.deleteUsers();

      // Launching the login activity
      Intent intent = new Intent(MainActivity.this, LoginActivity.class);
      startActivity(intent);
      finish();
   }
}

Now if you run the app, you should see the below screen after successful login.

android Dashboard screen layout

5. Testing the App

For a beginner it will be always difficult to run this project for the first time. But don’t worry, the following steps will helps you testing this app. (The ip address looks like 192.168.0.200)

  • Make sure that both devices (the device running the PHP project and the android device) are on the same wifi network.
  • Give correct username , password and database name of MySQL in Config.php.
  • Replace the URL ip address of URL_LOGIN and URL_REGISTER in AppConfig.java with your Machine ip address. You can get the ip address by running ipconfig in cmd.

Download Android Code Download PHP Code

Happy Coding 🙂