In my previous article Android Login and Registration Screen Design I explained designing the login and registration interfaces. But it has no real time functionality. 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.

android login and registration screen design

Below are the final outputs of this project.

android login and registration with mysql php

Prerequisites

This tutorial is combination of few of my previous articles. Make sure you went through the below articles if you are very beginner.

1. Android working with Volley Library – Used to make HTTP calls.

2. Android Login and Registration Screen Design – Explained the designing of Login and Registration screens.

API (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

Android Mysql PHP connect

1. Downloading & Installing WAMP

Download & Install WAMP server from www.wampserver.com/en/. Once installed, launch the program from Start ⇒ All Programs ⇒ WampServer ⇒ StartWampServer. If you are on Mac, alternatively you can use MAMP for the same.

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

Following is a screencast of Downloading and Installing WAMP Server.

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.

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 wamp installed and open www folder. The default installation location of wamp would be C:/wamp. Below is the final PHP project structure we are going to create in this article.

android-login-and-registration-project-structure

1. Go into www 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.

<?php

/**
 * Database config variables
 */
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
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.

<?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.

<?php

/**
 * @author Ravi Tamada
 * @link https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ Complete tutorial
 */

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.

<?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.

<?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": "55fa7220a2c187.50984590",
    "user": {
        "name": "Ravi Tamada",
        "email": "ravi@androidhive.info",
        "created_at": "2015-09-17 13:26:16",
        "updated_at": null
    }
}

Registration error in storing

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

Registration error – User Already Existed

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

{
    "error": false,
    "uid": "55fa7220a2c187.50984590",
    "user": {
        "name": "Ravi Tamada",
        "email": "ravi@androidhive.info",
        "created_at": "2015-09-17 13:26:16",
        "updated_at": null
    }
}

Login error – Incorrect username / password

{
    "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 Project and fill all the required details.

2. Create three packages named app, activity and helper under src folder.

3. Open build.gradle and add volley library support by adding
compile ‘com.mcxiaoke.volley:library-aar:1.0.0’ under dependencies.

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

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">Android Login and Registration</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 Me.</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. If you don’t find colors.xml, create a new file with the name.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="bg_login">#26ae90</color>
    <color name="bg_register">#2e3237</color>
    <color name="bg_main">#428bca</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">#5e6266</color>
    <color name="btn_login">#26ae90</color>
    <color name="btn_login_bg">#eceef1</color>
    <color name="lbl_name">#333333</color>
    <color name="btn_logut_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.

package info.androidhive.loginandregistration.app;

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

	// Server user register url
	public static String URL_REGISTER = "http://192.168.0.102/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.

package info.androidhive.loginandregistration.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="info.androidhive.loginandregistration"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="info.androidhive.loginandregistration.app.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            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=".RegisterActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" />
        <activity
            android:name=".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 User Session Management using Shared Preferences gives you a good overview of managing the session data using SharedPreferences.

package info.androidhive.loginandregistration.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
	SharedPreferences pref;

	Editor editor;
	Context _context;

	// Shared pref mode
	int PRIVATE_MODE = 0;

	// Shared preferences file name
	private static final String PREF_NAME = "AndroidHiveLogin";
	
	private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

	public SessionManager(Context context) {
		this._context = context;
		pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
		editor = pref.edit();
	}

	public void setLogin(boolean isLoggedIn) {

		editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);

		// commit changes
		editor.commit();

		Log.d(TAG, "User login session modified!");
	}
	
	public boolean isLoggedIn(){
		return pref.getBoolean(KEY_IS_LOGGEDIN, 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.

/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 * */
package info.androidhive.loginandregistration.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.

<?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/white"
            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/white"
            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/btn_login_bg"
            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.

/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 */
package info.androidhive.loginandregistration.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.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import info.androidhive.loginandregistration.R;
import info.androidhive.loginandregistration.app.AppConfig;
import info.androidhive.loginandregistration.app.AppController;
import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    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 = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) 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 the credentials!", 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(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.

android login screen design

4.1 Adding the Registration Screen

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

<?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="#ea4c88"
            android:text="@string/btn_register"
            android:textColor="@color/white" />

        <!-- 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.

/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 */
package info.androidhive.loginandregistration.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.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import info.androidhive.loginandregistration.R;
import info.androidhive.loginandregistration.app.AppConfig;
import info.androidhive.loginandregistration.app.AppController;
import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    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_register);

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

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

        // Session manager
        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(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 registration screen design

4.3 Adding the Home Screen

Until now we are done with both login and registration screen. Now we’ll add the final 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.

<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"
    tools:context="${relativePackage}.${activityClass}" >

    <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: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_logut_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.

package info.androidhive.loginandregistration;

import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView txtName;
	private TextView txtEmail;
	private Button btnLogout;

	private SQLiteHandler db;
	private SessionManager session;

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

		txtName = (TextView) findViewById(R.id.name);
		txtEmail = (TextView) findViewById(R.id.email);
		btnLogout = (Button) 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 welcome dashboard screen after login

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.100)

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

What’s Next?

If you understand this article very clearly, its time to improvise your knowledge by following the below articles.

> Read How to create REST API for Android app using PHP, Slim and MySQL to learn how to develop a proper REST API for your android app.

> Android Hosting PHP, MySQL RESTful services to DigitalOcean explains how to deploy your REST services online. So that the urls will be accessible globally.

Change Log

Updated On 28th Feb 2016 (Android Studio IDE)
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Pingback: Android Login and Registration with PHP, MySQL and SQLite … | Programmer Solution()

  • Pingback: Ndroid textcolor | Etiquefacere()

  • Pingback: NullException error in simple loging app()

  • Pingback: HttpPost android: 500 Server error with name value pairs , 200 ok without name value pairs in url()

  • Pingback: HttpPost android: 500 Server error with name value pairs , 200 ok without name value pairs in url • PHP Help Coding Programming()

  • Pingback: Android info | Bejegyzések főleg az informatika területéről()

  • rajeev

    Hi Getting error Required param name or email or password is missing can u please tell me what is the error

    Here is the android conection source code can u please let me know what is the error

    URL url = new URL(“http://192.168.43.113/android_login_api/register.php”);

    HttpURLConnection http = (HttpURLConnection)url.openConnection();

    //if(http.getResponseCode() == HttpURLConnection.HTTP_OK){
    Log.d(“con”,” “+”Connected…”);
    // http.setRequestMethod(“POST”);

    http.setRequestMethod(“POST”);
    http.setDoInput(true);
    http.setDoOutput(true);

    String username = URLEncoder.encode(“namee”,”UTF-8″) +”=” +URLEncoder.encode(“suresh”,”UTF-8″);
    String email = “&”+URLEncoder.encode(“email”,”UTF-8″) +”=”+ URLEncoder.encode(“suresh@gmail.com”,”UTF-8″);
    String password = “&”+URLEncoder.encode(“password”,”UTF-8″)+”=” +URLEncoder.encode(“123456″,”UTF-8”);

    String temp = username + email + password;

    Log.d(“con”,” “+” “+temp );
    OutputStream os = http.getOutputStream();
    OutputStreamWriter os1 = new OutputStreamWriter(os);
    os1.write(temp);

    os1.flush();
    os1.close();

    Log.d(“con”,” “+”Connecting for input “+http.getResponseCode());
    //if(http.getResponseCode() == HttpURLConnection.HTTP_OK){

    Log.d(“con”,” “+”Connecteddddd for input “);

    InputStream is = http.getInputStream();
    BufferedReader reader = new BufferedReader(new
    InputStreamReader(http.getInputStream()));
    String line;
    StringBuilder sr = new StringBuilder();
    while ((line = reader.readLine())!=null){

    sr.append(line);

    }

    is.close();
    reader.close();
    Log.d(“con”,sr.toString());

  • Karan Brahmaxatriya

    hey Ravi sir i m using ur code its work perfectly bt after login and register successfully not going to next activity please help me to go other activty after login its imp

    • Check the LogCat for any errors.

      • Karan Brahmaxatriya

        Getting this in Log Cat file
        Login Response: {“VerifiedMember”:[{“user_id”:”76″,”first_name”:”A”,”phone”:””}],”success”:1,”message”:”success”}

      • Karan Brahmaxatriya

        bt not going to new activity

        • Pls post the code where the json is parsed and activity is launched.

          • Karan Brahmaxatriya

            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(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener() {

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

            try {
            JSONObject jObj = new JSONObject(response);
            int intError = jObj.getInt(“success”);
            boolean error = (intError > 0) ? true : false;

            /*
            boolean error = jObj.getBoolean(“success”);
            */

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

            // Now store the user in SQLite

            JSONObject user = jObj.getJSONObject(“VerifiedMember”);
            String first__name = user.getString(“first_name”);
            String email = user.getString(“phone”);

            // Launch main activity
            Intent intent = new Intent(LoginActivity.this,
            MainActivity.class);
            startActivity(intent);
            finish();

            // Inserting row in users table
            db.addUser(first__name, email);

            } else {
            // Error in login. Get the error message
            String errorMsg = jObj.getString(“message”);
            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 getParams() {
            // Posting parameters to login url
            Map params = new HashMap();
            params.put(“username”, email);
            params.put(“password”, password);

            return params;
            }

            };

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

          • Karan Brahmaxatriya

            sir pls have a look on it its urgent for me

          • Karan Brahmaxatriya

            Wt happen?
            pls help me

          • Where is the code?

          • Karan Brahmaxatriya

            posted it twice pls check it and solve it

          • Is there finish() statement in MainActivity?

          • Karan Brahmaxatriya

            yes

          • Karan Brahmaxatriya

            Yes

          • Karan Brahmaxatriya

            Getting this in Log Cat file
            Login Response : {“VerifiedMember”:[{“user_id”:”23″,”first_name”:”karan”,”phone”:””}],”success”:1,”message”:”success”}

          • Karan Brahmaxatriya

            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(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener() {

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

            try {
            JSONObject jObj = new JSONObject(response);
            int intError = jObj.getInt(“success”);
            boolean error = (intError > 0) ? true : false;

            /*
            boolean error = jObj.getBoolean(“success”);
            */

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

            // Now store the user in SQLite

            JSONObject user = jObj.getJSONObject(“VerifiedMember”);
            String first__name = user.getString(“first_name”);
            String email = user.getString(“phone”);

            // Launch main activity
            Intent intent = new Intent(LoginActivity.this,
            MainActivity.class);
            startActivity(intent);
            finish();

            // Inserting row in users table
            db.addUser(first__name, email);

            } else {
            // Error in login. Get the error message
            String errorMsg = jObj.getString(“message”);
            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 getParams() {
            // Posting parameters to login url
            Map params = new HashMap();
            params.put(“username”, 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();
            }
            }

  • Karan Brahmaxatriya

    Any one can help me please unable to go new activity after succefully login and register pls help me to slove this issue….

  • Hardik Ajmera

    Sir I’m using your code but app crashes as soon as I click on Register Button can you pls help me

    • Check your LogCat for errors.

      • Hardik Ajmera

        my LOGCAT
        at android.view.View.performClick(View.java:5637)

        at android.view.View$PerformClick.run(View.java:22429)

        at android.os.Handler.handleCallback(Handler.java:751)

        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)

        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)

  • Josue Carrillo

    Hi! im getting the error ” json error: value <br of type java.lang.String cannot be converted to JSONObject android " Any idea..?

    • Josue Carrillo

      my logcat:

      org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
      07-17 17:23:46.027 881-881/info.androidhive.loginandregistration W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
      07-17 17:23:46.027 881-881/info.androidhive.loginandregistration W/System.err: at org.json.JSONObject.(JSONObject.java:160)
      07-17 17:23:46.027 881-881/info.androidhive.loginandregistration W/System.err: at org.json.JSONObject.(JSONObject.java:173)
      07-17 17:23:46.027 881-881/info.androidhive.loginandregistration W/System.err: at info.androidhive.loginandregistration.activity.LoginActivity$3.onResponse(LoginActivity.java:126)
      07-17 17:23:46.027 881-881/info.androidhive.loginandregistration W/System.err: at info.androidhive.loginandregistration.activity.LoginActivity$3.onResponse(LoginActivity.java:118)

  • Works like a charm! Thank you!

  • Sewak

    Hello i sucessfully register but when i click login nothing happens why? no going to main activity?

  • Sewak Singh

    unable to download new code i have V2 send me new one on sewaksm@gmail.com

  • Agi Arif

    sir.. im having problem with this code:
    import info.androidhive.loginandregistration.R;

    cannot resolve symbol ‘R”.. how the solution with my problem.. help me thanks..

    • Ciaran Callaghan

      import info.androidhive.loginandregistration.R;
      this should be:
      import {the name of your package}.R;

  • Vir Bhatt

    Hello Ravi,
    I am getting error in get_result() in DB_Functions.php.

    When I am sending the request from Advanced Rest Client. It is giving this :

    Fatal error: Call to undefined method mysqli_stmt::get_result() in C:xampphtdocsandroid_login_apiincludeDB_Functions.php on line 21

  • Hikigaya Hachiban

    Hello Ravi,
    i am new to programming and i followed your tutorial but when i run it, it shows nothing, the screen will only become white. just that….

    what should i do about it?
    please help!

  • Chinmay Bakshi

    App is installed but as soon as i open the app it crashes.

    • Check the LogCat for errors!

      • Hikigaya Hachiban

        Hello Ravi,
        the application still view the white screen, is it possible that the android version is not compatible with my emulator?

  • Gemson Gonzales

    Good day Ravi, I’m using your program and made it work perfectly except for one thing. When an account is logged in for the first time this error shows up but I believe it does nothing to the activity

    E/SQLiteLog: (2067) abort at 14 in [INSERT INTO user(email,name,created_at,uid) VALUES (?,?,?,?)]: UNIQUE constraint failed: user.email
    E/SQLiteDatabase: Error inserting email=tryhard@gmail.com name=tryhard created_at=2017-07-27 10:50:06 uid=597954de2753f3.76395920
    android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: user.email (code 2067)

    It only shows when a user is logged in for the first time on second login it doesn’t show up. It’ll be a great help if you can give me your idea about what causes this error

    • Gemson Gonzales

      i already fixed this by adding CONFLICT_REPLACE on insert method. Just in case someone get this error here’s what i did.
      you need to import this one:
      import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE;
      then declare it as int “private static int conflictAlgorithm = CONFLICT_REPLACE;”
      and I replaced my insert code with this:
      long id = db.insertWithOnConflict(TABLE_USER, null, values, conflictAlgorithm);

      Thank you for this example Ravi, great help now I can start with what i want to do

      • I think this causes a problem. Make sure you are not deleting older account, may be that can be somebody else’s account.

    • Hi Gemson

      You are inserting an email which is already existed in db. You need to check if it’s present already, then only insert the new email.

  • Gemson Gonzales

    Good day Ravi, I used your program and made it work but I got this error that I believe does nothing to the activity The first time you logged in a user this error shows up

    E/SQLiteLog: (2067) abort at 14 in [INSERT INTO user(email,name,created_at,uid) VALUES (?,?,?,?)]: UNIQUE constraint failed: user.email
    E/SQLiteDatabase: Error inserting email=whatever@gmail.com name=whatever created_at=2017-07-27 11:06:23 uid=597958afbf2a73.40056887
    android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: user.email (code 2067)

    This only shows up on first time log in of the user, on second log in and so on it doesn’t show up anymore. What do you think causes this error? Would be a great help if you can give me your idea about this.

  • kelvin skip

    hello my login is givin a json error and my registration details do not go to the database please help.

  • Chinmay Bakshi

    Hey My data is entered in data base but when i am trying to login it show an error and not letting me to move from login screen check out the screenshot
    My data is being entered but not displayed https://uploads.disquscdn.com/images/9079de8fad8bdea5a356042d1c9c125b49c708e94834e9d8314925756a88f3d5.png

    https://uploads.disquscdn.com/images/bc85b2e11114b0ca09c8b31d938a1b077c3f208d31a0698c5f19e346a71083e6.png

    log cat -> https://uploads.disquscdn.com/images/9b4d02aebc62eb2324d8998fca55627fe7c72b189ee0102bf351f0759d6fdd26.png

    • Hit the login url from Postman and see whether you are getting proper json or not.

  • madDY

    sir i have an issue…. after inserting the fields of registration from android emulator, then its not save in mySQL database ….. can you please tell me?????????

    • Thirumani Mohan kumar

      i found same problem . Can anybody solve this? plz replay fast.

  • Vu Dinh Phong

    What is the Different if we extends class from Activity vs AppCompatActivity? thank you!

  • shashi patil

    why didn’t you wrote any examples on service and intent service… it will help to understand better for many people… thank you

  • umer

    {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

    {“error”:true,”error_msg”:”Required parameters email or password is missing!”}

    i did everything correct then why i have this error
    plzzz help me

    • You are not sending the request parameters. Give your android request code.

      • Hamza Abidi

        i have a time out problem
        @Override
        public void onErrorResponse(VolleyError error) {
        if(error instanceof TimeoutError)
        Log.e(TAG, “Login Error: TIME OUT ERROR”);
        else if(error instanceof ServerError)
        Log.e(TAG, “Login Error: SERVER ERROR”);
        Log.e(TAG, “Login Error: ” + error.getMessage());
        Toast.makeText(context.getApplicationContext(),
        “Login Error: ” + error.getMessage(), Toast.LENGTH_LONG).show();
        hideDialog();
        }

        i tried to change the time out by doing this but
        I still have the same problem :

        strReq.setRetryPolicy(new DefaultRetryPolicy(
        AppConfig.MY_SOCKET_TIMEOUT_MS, // 1000*15
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

      • Farly Wuwungan

        i have a same problem. i dont know where the code.
        can you give android request code example?

        • Hi Farly

          You have to understand the code correctly otherwise your life becomes tougher . Try to understand the article and read every line of code.

  • trupti

    Working on localhost but on server error occur Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/android_login_api/include/DB_Functions.php

    • Ananda Satriyo

      your function.php name see it bro and you will realize, i got confused for a moment too
      just rename the fuction.php file and it will resolve your rob

      • hugo

        What do you mean “rename”?

        Rename the archive DB_FUNCTIONS to E.g DB_FUNC
        or rename Line 64: $user = $stmt->”get_result()”->fetch_assoc();
        to $user = $stmt->”get_results()”->fetch_assoc(); ?

        Explain me because i have the same problem in my own server :/

        • EFabricio Vera Núñez

          Could you solve it?

  • Ananda Satriyo

    I got so confusing error massage, when i got clicked the register button, i got a error dialog mesagge it says {“error”:true,”error_msg”:”Login credentials are wrong. Please try again!”}

    and from the logcat just showing this error
    can you help me?

    08-04 17:04:36.753 31150-31150/com.example.fallen.loginphp I/ViewRootImpl: CPU Rendering VSync enable = true
    08-04 17:04:36.793 31150-31150/com.example.fallen.loginphp I/ViewRootImpl: CPU Rendering VSync enable = true
    08-04 17:04:38.663 31150-31150/com.example.fallen.loginphp I/ViewRootImpl: CPU Rendering VSync enable = true
    08-04 17:04:39.763 31150-31150/com.example.fallen.loginphp D/RegisterActivity: Register Response: {“error”:true,”error_msg”:”Login credentials are wrong. Please try again!”}
    08-04 17:04:39.783 31150-31150/com.example.fallen.loginphp W/Toast: From com.example.fallen.loginphp, go ahead.
    08-04 17:04:39.793 31150-31150/com.example.fallen.loginphp I/ViewRootImpl: CPU Rendering VSync enable = true

    • Thirumani Mohan kumar

      use “$_GET” in place of “$_POST” in file register.php

  • sandhita mittal

    Hi. My registration is working successfully but I am getting this error when i use the login activity.
    BasicNetwork.performRequest: Unexpected response code 500

    Please help.

    • It seems you have php / mysql error. Check apache /php error logs .

      • sandhita mittal

        Hi Ravi. Thanks for the prompt reply. I am not getting that error anymore. But php file is unable to read my parameters. I am getting {“error”:true,”error_msg”:”Required parameters email or password is missing!”} in my android logcat. Please advise.

        • Can you try the url with Postman or paste the android request code here.

          • sandhita mittal

            It’s not working with POSTMAN also. My login.php is as below:

            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!”;

            }
            } else {
            // required post params is missing
            $response[“error”] = TRUE;
            $response[“error_msg”] = “Required parameters email or password is missing!”;
            echo json_encode($response);

            }
            ?>

            Android Login code is as below:

            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();

            Log.i(“login”, “login”);
            StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener() {

            @Override
            public void onResponse(String response) {

            Log.d(TAG, “Login Response: ” + response.toString());
            hideDialog();

            }
            }, 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 getParams() throws AuthFailureError {
            // Posting params to register url
            Map params = new HashMap();

            params.put(“email”, email);
            params.put(“pass”, password);

            return params;
            }

            };

          • sandhita mittal

            sorry this is the correct android code.

            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(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener() {

            @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 getParams() {
            // Posting parameters to login url
            Map params = new HashMap();
            params.put(“email”, email);
            params.put(“password”, password);

            return params;
            }

            };

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

          • sandhita mittal

            And my postman query is using raw, application/json.

            {
            “email”: “a@a.com”,
            “password”:”pop”

            }

  • Shivam Goyal

    hello ravi,
    i want to login or register by phone number otp, how should i change the program so that it give me results.

  • cyah

    hi, i added more columns to my table “users” and when i register the user it gives me the error ‘unknown error occurred in registration’ but when i remove those columns, it works fine. why am i getting the error?

  • Nikhil patil

    https://uploads.disquscdn.com/images/3e592276d366568df58e21cb1fc9dcedd0534d6275ae6685108fd5c37ada7dca.png my rest api is not working getting error {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”} but i am giving the params ,i am testing it in postman

    • Marhan S Rogers

      hi i got the same error, how do i resolve this? pls..

  • ara

    hi. i try this code but when i click button login it stop.why?

  • Mohamed Zaid Farook

    I followed the entire tutorial but i am struggling to connect using the request code. When i ran the request code in postman i get the same message as above. I get a java.net.connect Exception. I am trying for a long time can u pls help?

    • stanley

      Same

  • Padmanabham Vishwakarma

    Hi..I am always getting below message :
    Required parameters email or password is missing!”;

  • Muhamad Bagzada

    Great work Mr.Ravi , It’s successfully but i want to showing all data in database(online) by ListView !?

  • Merve

    Hi,there is a problem.
    E/DataScheduler: isDataSchedulerEnabled():false
    E/RegisterActivity: Registration Error: null Why and how to solve this?

  • Merve

    in addition ,{“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

  • Vu Dinh Phong

    Why do we use StringRequest? I try to change to JsonObjectRequest but it gave me error, since the json response start with { . Thank you!

  • Oliver

    Dear Ravi,
    I compare all codes with yours, all are the same, but when I run app, it crashes! Logcat points to some Null pointer Exception! I think it has problem with sending params in post method .
    I checked all things , but I can’t find the problem, please help me ..
    thanks.

    • Check This AppController added or not in your manifest

      • Marhan S Rogers

        hi thanks it worked!

  • Nabeel Hafeez

    Hi Ravi,
    How import DB in PHPMyAdmin?
    When I try to import the error shown below:
    #1064 – You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘use android_api

    • php syntax error find and fix and try again

    • CJ Caimoy

      COPY AND PASTE THE CODE BELOW

      create database android_api ;
      use android_api;

      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
      );

  • طیبہ علاؤالدین

    app crashes ,plzz help,logcat error:
    08-19 02:34:23.759 3707-3707/? I/art: Not late-enabling -Xcheck:jni (already on)
    08-19 02:34:23.760 3707-3707/? W/art: Unexpected CPU variant for X86 using defaults: x86
    08-19 02:34:23.882 3707-3707/? W/System: ClassLoader referenced unknown path: /data/app/com.example.tayyibah.androidloginandregistration-2/lib/x86
    08-19 02:34:23.939 3707-3707/com.example.tayyibah.androidloginandregistration I/InstantRun: Instant Run Runtime started. Android package is com.example.tayyibah.androidloginandregistration, real application class is com.example.tayyibah.androidloginandregistration.app.AppController.
    08-19 02:34:26.731 3707-3707/com.example.tayyibah.androidloginandregistration W/System: ClassLoader referenced unknown path: /data/app/com.example.tayyibah.androidloginandregistration-2/lib/x86
    08-19 02:34:26.817 3707-3707/com.example.tayyibah.androidloginandregistration W/ResourceType: Failure getting entry for 0x7f0b0001 (t=10 e=1) (error -75)
    08-19 02:34:26.818 3707-3707/com.example.tayyibah.androidloginandregistration D/AndroidRuntime: Shutting down VM
    08-19 02:34:26.819 3707-3707/com.example.tayyibah.androidloginandregistration E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tayyibah.androidloginandregistration, PID: 3707
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tayyibah.androidloginandregistration/com.example.tayyibah.androidloginandregistration.activity.LoginActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class
    Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
    at android.view.LayoutInflater.createView(LayoutInflater.java:645)
    at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:414)
    at android.app.Activity.setContentView(Activity.java:2414)
    at com.example.tayyibah.androidloginandregistration.activity.LoginActivity.onCreate(LoginActivity.java:47)
    at android.app.Activity.performCreate(Activity.java:6662)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Caused by: android.content.res.Resources$NotFoundException: Drawable com.example.tayyibah.androidloginandregistration:color/bg_login with resource ID #0x7f0b0001
    Caused by: android.content.res.Resources$NotFoundException: Resource “com.example.tayyibah.androidloginandregistration:color/bg_login” (7f0b0001) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f0b0001 a=-1 r=0x7f0b0001}
    at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:687)
    at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
    at android.content.res.Resources.loadDrawable(Resources.java:854)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:928)
    at android.view.View.(View.java:4175)
    at android.view.ViewGroup.(ViewGroup.java:578)
    at android.widget.LinearLayout.(LinearLayout.java:211)
    at android.widget.LinearLayout.(LinearLayout.java:207)
    08-19 02:34:26.820 3707-3707/com.example.tayyibah.androidloginandregistration E/AndroidRuntime: at android.widget.LinearLayout.(LinearLayout.java:203)
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
    at android.view.LayoutInflater.createView(LayoutInflater.java:645)
    at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:414)
    at android.app.Activity.setContentView(Activity.java:2414)
    at com.example.tayyibah.androidloginandregistration.activity.LoginActivity.onCreate(LoginActivity.java:47)
    at android.app.Activity.performCreate(Activity.java:6662)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

  • Mam3adegh Salehi

    hi, thanks a lot ravi, i have this error when using register form:

    E/Volley: [4410] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.1.4/android_free_api/register.php

    can anyne help me!?

  • Daffodills Solutions

    Hi Ravi,

    I like your code. It is works fine. This is totally free api right? Is there any licence. I am going to use in my project thats why am asking.

    Thanks,
    Daffo

  • Bouna Nadia

    Hi Ravi
    Thanks for the tuto but my problem is that i can’t turn on wifi on my android emulator so i can’t test the app . I tried to install adb wifi plugin but the problem consist… i saw on your demo video that you have used android emulator and not an usb device and i want to do the same thing because i dont have an android smartphone to connect it via usb.. i have iphone…i hope you answer me soon thank you ^_^

  • Dhwani Bhansali

    hey,
    At the time of submitting data to database I’m getting error that “Forbidden, you don’t have permission to access database on this server” I also have tried by changing permissions into httpd.conf but it didn’t work. please help me

  • Youssif Al Shamali

    Hi Ravi,
    when im trying to register or login this Toast Appears : java.net.connectexception connection refused

    what it means and why this happens ??
    no changes happen in the mysql !!

    Thanks in Advance
    Yousif Alshamali

    • Mohammad Mirzakhani

      i have the same problem.
      anybody can help?

  • Achabla

    Hi Ravi, I have a slightly strange problem. When I try to register on online database. It registers, but doesn’t show the response. When I press The Register Button again it says user already exist, and then I find it in the database. However the Login button doesn’t work. What could be the problem.

  • Hamza Abidi

    i have a time out problem
    @Override
    public void onErrorResponse(VolleyError error) {
    if(error instanceof TimeoutError)
    Log.e(TAG, “Login Error: TIME OUT ERROR”);
    else if(error instanceof ServerError)
    Log.e(TAG, “Login Error: SERVER ERROR”);
    Log.e(TAG, “Login Error: ” + error.getMessage());
    Toast.makeText(context.getApplicationContext(),
    “Login Error: ” + error.getMessage(), Toast.LENGTH_LONG).show();
    hideDialog();
    }

    i tried to change the time out by doing this but
    I still have the same problem :

    strReq.setRetryPolicy(new DefaultRetryPolicy(
    AppConfig.MY_SOCKET_TIMEOUT_MS, // 1000*15
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

  • Auston Ajith

    @ravi8x:disqus There is a spelling mistake in your post which makes mysql problems
    correct this “DB_Functons.php” to “DB_Functions.php”

  • Panchal Vipul

    {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

    i have try a lot but getting this error

  • samsul marif

    you can help me please

    {

    error: true,

    error_msg: “Required parameters (name, email or password) is missing!”

    }

    i dont understand about this

  • Rajesh Kannan

    {“error”:true,”error_msg”:”Required parameters email or password is missing!”}
    in my login.php file

    in my app not show any error but I am unable login or register

    i need help…………….

    • You are not sending the email and password in the request. Paste your login request code.

  • Muhammad Fauzan

    I dont know the problem is i do same with ur tips and little modification on API but when im run it
    it always close https://uploads.disquscdn.com/images/1ec01c40359acde93f3d4e54061c96287606bab0dcdfcf356c37c30ea92297e1.png

    • Check LogCat for errors.

      • Muhammad Fauzan

        is it take effect when im using external emulator such as nox player..?

  • It seems you haven’t added LoginActivity to your AndroidManifest.xml

    • Muhammad Fauzan

      im already added loginActivity on my androidmanifest but its still closes

      FATAL EXCEPTION: main
      Process: com.develop.almaz.ibibi, PID: 4515
      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.develop.almaz.ibibi/com.develop.almaz.ibibi.MainActivity}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.develop.almaz.ibibi/com.develop.almaz.ibibi.activity.LoginActivity}; have you declared this activity in your AndroidManifest.xml?
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
      at android.app.ActivityThread.access$800(ActivityThread.java:135)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:136)
      at android.app.ActivityThread.main(ActivityThread.java:5019)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
      at dalvik.system.NativeStart.main(Native Method)
      Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.develop.almaz.ibibi/com.develop.almaz.ibibi.activity.LoginActivity}; have you declared this activity in your AndroidManifest.xml?
      at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1645)
      at android.app.Instrumentation.execStartActivity(Instrumentation.java:1441)
      at android.app.Activity.startActivityForResult(Activity.java:3424)
      at android.app.Activity.startActivityForResult(Activity.java:3385)
      at android.app.Activity.startActivity(Activity.java:3627)
      at android.app.Activity.startActivity(Activity.java:3595)
      at com.develop.almaz.ibibi.MainActivity.logoutUser(MainActivity.java:75)
      at com.develop.almaz.ibibi.MainActivity.onCreate(MainActivity.java:41)
      at android.app.Activity.performCreate(Activity.java:5231)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
      at android.app.ActivityThread.access$800(ActivityThread.java:135)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:136)
      at android.app.ActivityThread.main(ActivityThread.java:5019)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
      at dalvik.system.NativeStart.main(Native Method)

  • Nihal Singh

    Unexpected response code 403 for http://192.168.43.203/android_login_api/register.php

    GETTING above error in logcat when I press on REGISTER, nothing happens, what to do ?

  • Anmol Kumar

    Hi Ravi,
    First of all, thank you for all your great tutorials and codes, helped me immensely in various projects..
    I have ran into some issues with the Android Login And Registration project..
    User registration gets entered into the database (using sql database on web – not local PC),
    But when using same details to login, does not work..
    Nothing happens and just a small greyish black circle comes up towards the bottom of the screen..
    Appreciate any assistance on this..
    Thanks

    • Call the same url from Postman by sending proper parameters and see what json response you are getting. Also check your apache / php logs for any errors.

      • Anmol Kumar

        looking into logcat,
        i see below

        E/Volley: [1290] BasicNetwork.performRequest: Unexpected response code 500

        • Ok. It’s throwing 500 error. Check the apache / php error logs on server.

  • avishkar walunj

    Hi, i have create mysql database using wamp server use php. if i login then json get the data . i want to send that data navigation drawer menu item layout.

    Like Home is fragment class -> name,email,phone,add
    renewal -> option netbanking , debit card payment i use activity i want to send here id,plan etc. how can i send the data.

  • Keshav Verma

    my error comes when i run php code
    mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:xampphtdocsandroidincludeDB_Connect.php on line 15
    {“error”:true,”error_msg”:”Required parameters email or password is missing!”}

    • Have you provided correct mysql username, password in config.php

  • Mukul Lashkari

    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.example.mukullashkari.onlinetestportal.APP.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)’ on a null object reference

    • Devendra

      <application
      android:name="Your_application_name.app.AppController"
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"

      add android:name after application tag.

  • Mukul Lashkari
  • Pedro Ivan Sanchez Portocarrer

    amigo muchas gracias excelente tutorial me ayudo mucho, estoy tratando de enviar 4 variables (name, email, password, CI) a la base de datos, que cambios deberia realizar?

    friend many thanks excellent tutorial helped me a lot, I am trying to send 4 variables (name, email, password, CI) to the database, what changes should I make?

    • Instead of trying blindly it’s better to understand the article fully. Learn the below article to build a proper REST api.
      https://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/

      If you want to do the changes in the same article, add your parameters both in android and server side too.

      In Android add here

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

      return params;
      }

      In php read them in register.php file. You can understand the code in that file easily.

  • Asim Hussain

    Ravi do you have video tutorial of the above login app code

    • No Asim. Whats the difficulty you are feeling in this article?

  • Seems to be there is PHP errors. Try hitting the urls from Postman and see the response.

  • KARTHIKEYAN A

    Make sure that both devices (the device running the PHP project and the android device) are on the same wifi network.
    how change it ?
    while i am trying login it not connect .i want to run php in one wifi network and application in another network
    please help me sir

    • Your both the devices (PC and Mobile) has to be there in the same network (won’t work on LAN again). Once both are connected, your pc ip should be accessible in mobile chrome browser.

  • Hasan Rahman Sawan

    Hi Ravi, I am having an interesting issue. Once I have logged in using one user, i kept on getting into the same user no matter whatever credential I give. On the other hand, when I enter a wrong details right after launching the app, it gives the expected error message. But afterwards it doesnt log me in no matter what. I checked with the API response by returning the email. It kept on returning the same(1st entered) email. Somehow my params are not changing. Any idea?

  • Md. Azizul Alam (Toton)

    Hi Ravi, Nice tutorial for beginner. Can you let me know how I can implement one time login in my App using this code? Actually I wanted to implement one time login. User will login once and there is no Logout in my App. I will be wonder if this can be done with this code. Thanks

    • You can do that using SharedPreferences. Store a boolean values login true in prefs. When the app is launched, check for this value and go to appropriate screen.

  • Rajeev sah.

    thank you so mauch sir,this code is so simple and easy to understand ….can you pls help me…i want to store the user details with there images and once he successfully login the username and image is shown.

  • priya sonpure

    very useful articles for beginner.. thank you so much ravi.. 🙂

  • Rem Marvida

    Hello Ravi I’m having a little bit of problem when i login the details are not there.

  • Luis Feria

    https://uploads.disquscdn.com/images/f8e81345027ce7d187089c7a040d6c78312ea61961fee9ea625824734c4947fd.png hola amigo, tengo problemas para el login, tambien me devuelve un mensaje vació

  • Bernardo Feria

    How do I connect it to my domain?

  • Ashkan Omidi

    my app crash when I click login or register button

  • saihemanth thota

    {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}
    iam getting this error please help me

    • Ammar Nafi Al Abbaz

      check the parameter in your postman

  • Ammar Nafi Al Abbaz

    can you make for forgot password?

  • Seyyed Naser Bahador

    Hi there, thanks for your tutorial. I have a question though: “Is this method secure?” if i host my DB on a website so that people can login from around the world then it seems that the “plain” password is sent to server. Is it okay or should i do something about it?

  • Ammar Nafi Al Abbaz

    plz help ravi… i testing for JSON response in POSTMAN and the response is

    {“error”:true,”error_msg”:”Unknown error occurred in registration!”}

    • Seems there are php errors. Check your php error logs.

      • Ammar Nafi Al Abbaz

        I’ve followed your tutorial but still can not

  • Atharva Karanje

    When I run the app, It runs fine on emulator but on the device it shows connection time out exception, please help

    • Is the device is in the same wifi network? Check whether you can access the pc IP in device’s browser

  • Przemysław Walczak

    I have problem. error : {“error”:true,”error_msg”:”Required parameters email or password is missing!”} . help me

    • You are not sending the required parameters. Can you post your code of http request.

  • prashant maheshwari

    Ravi Sir Plz Help me, I want to add Second Factor Authentication as OTP here After Login and Register. Plz provide that Code. I need It really Urgent.

      • prashant maheshwari

        but sir here i need to use both of them in single app so that first user login himself and after that verifies him by otp. so suggest me such type of article.

        • You need to learn and integrate them in one app. That’s what developers are for.

          • prashant maheshwari

            Thank You For Such Great Articles.
            But Can u suggest one more Article for data Sharing Within the App without Internet.
            This will help me alot.
            Thank u once again.

          • Could you describe this a bit ‘data Sharing Within the App’

          • prashant maheshwari

            means Just as in whatsapp we can share text files and images.
            So i need implement such thing in my college project. plz suggest me such type of articles. Plz share to me. thank U sir

  • Pranav Arya

    Finally Issue Solved!!

    Add the AppController class to tag to AndroidManifest.xml file

  • Pranav Arya

    Finally Issue Solved!!
    .
    Add the AppController class to tag to AndroidManifest.xml file

  • Pranav Arya

    Finally Issue Solved!!

    Add the AppController class to tag to AndroidManifest.xml file

    ..

  • Md. Azizul Alam (Toton)

    It’s worked like charm with Localhost using Wamp. I am now uploading all stuff to production server and testing it. But Seems like there is something t=wrong with the PHP codes. I dont know what I am missing. I have tried with postman also. Here is the Postman screenshot. Fun part is register is inserting data but login is not working

    https://uploads.disquscdn.com/images/f9f485d24a3982fff3d712c07db6366c222d3270441e8b80a969ecbd3a607552.png

    • The parameters in POST method won’t go in url, they should go in post params. Check on Params button left to send and add your parameters.

      • Md. Azizul Alam (Toton)

        I got the Postman problem. Now I am doing the correct POST method using postman. But the problem is when I am doing the POST method using localhost its returning the values. But when I am trying the same thing using production server its now returning null/blank. Even when I am trying to Login through Apps a Blank Toast is appearing and not going to MainActivity intent. The difference in Header I found, the Localhost is using php 5.3.0 and the Production server is using Php 7.0.24. Dont know why this kind of behavior is happening

        • There might be php / mysql error. Check the error logs on your server.

  • bhagya

    I am getting and error both while login and registration : Null
    E/Volley: [192] BasicNetwork.performRequest: Unexpected response code 404

    I am not sure whats wrong as my code is exactly similar to yours.

    Can you please help me with this