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.

      • Death Star

        Thanks a ton for the response Ravi. Here it is
        [27-Oct-2017 13:41:47 UTC] PHP Warning: require(../scripts/config.inc.php): failed to open stream: No such file or directory in C:wamp64wwwbtcmcxindex.php on line 16

        [27-Oct-2017 13:41:47 UTC] PHP Stack trace:

        [27-Oct-2017 13:41:47 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxindex.php:0

        [27-Oct-2017 13:41:47 UTC] PHP Fatal error: require(): Failed opening required ‘../scripts/config.inc.php’ (include_path=’.;C:phppear’) in C:wamp64wwwbtcmcxindex.php on line 16

        [27-Oct-2017 13:41:47 UTC] PHP Stack trace:

        [27-Oct-2017 13:41:47 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxindex.php:0

        [27-Oct-2017 17:50:59 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:50:59 UTC] PHP Stack trace:

        [27-Oct-2017 17:50:59 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:50:59 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:51:16 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:51:16 UTC] PHP Stack trace:

        [27-Oct-2017 17:51:16 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:51:16 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:52:40 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:52:40 UTC] PHP Stack trace:

        [27-Oct-2017 17:52:40 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:52:40 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:54:43 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:54:43 UTC] PHP Stack trace:

        [27-Oct-2017 17:54:43 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:54:43 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:54:49 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:54:49 UTC] PHP Stack trace:

        [27-Oct-2017 17:54:49 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:54:49 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:54:50 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:54:50 UTC] PHP Stack trace:

        [27-Oct-2017 17:54:50 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:54:50 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:54:51 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:54:51 UTC] PHP Stack trace:

        [27-Oct-2017 17:54:51 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:54:51 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [27-Oct-2017 17:58:37 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [27-Oct-2017 17:58:37 UTC] PHP Stack trace:

        [27-Oct-2017 17:58:37 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [27-Oct-2017 17:58:37 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        [28-Oct-2017 07:41:24 UTC] PHP Fatal error: Call to a member function bind_param() on boolean in C:wamp64wwwbtcmcxincludeDB_Functions.php on line 36

        [28-Oct-2017 07:41:24 UTC] PHP Stack trace:

        [28-Oct-2017 07:41:24 UTC] PHP 1. {main}() C:wamp64wwwbtcmcxregister.php:0

        [28-Oct-2017 07:41:24 UTC] PHP 2. DB_Functions->storeUser() C:wamp64wwwbtcmcxregister.php:24

        • Death Star

          This is line 36 in DB_FUBCTIONS.php
          $stmt->bind_param(“sssss”, $uuid, $name, $email, $encrypted_password, $salt);

          • vips

            so what is missing here it seems all fine like ravi dictated and i m using local server wamp btw

          • ⇒ Make sure that both devices (the device running the PHP project and the android device) are on the same wifi network.

        • Seems the relative path is not working. Use __DIR__ before the path.
          https://stackoverflow.com/questions/5364233/php-fatal-error-failed-opening-required-file

          require_once __DIR__.'/../scripts/config.inc.php';

          • vips

            well i have also tried this but nothing happand,stil suffers with {“error”:true,”error_msg”:”Required parameters email or password is missing!”}’, i guess it is not able to get access to the parameters but anyhow i don’t understand this thing

          • hari

            Even I am facing the same issue

          • Rodrigue

            hi Ravi l have problem with php code fatal error require_once() failed opening required ‘include/DB_Functions.php’ (include_path=’.;C:phppear’) in C:Wampwwwandroid_login_api… how to solve that problem

          • Rodrigue

            hi Ravi l use now postman when l enter parameters name email password result is error_msg: unknown error occured in registration please help me by give me a maximun of details

      • Omar Balout

        Dear Ravi if i wanted to host my db on line how do i modify this to get values and save values on my server

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

          • Techlingda Tutorials

            no

        • Techlingda Tutorials

          I rename database name to android_api to carbon_android_api

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

    • Gerd Marinelli

      … just import piece by piece:

      create database android_api /** Creating Database **/

      then:

      use android_api /** Selecting Database **/

      then:

      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 **/

      Then all will be fine

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

    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?

      • Praful Dhabekar

        Have you inserted the right IP address in following code?

        //Server register url
        public static final String URL_REGISTER = “http://192.168.0.1/android_login_api/register.php”

        192.168.0.1 is mine IP Address, yours maybe different.

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

    • Mahantesh Gurav

      In register.php
      Adding if($user = true) worked for me.

      Here you have to add
      // create a new user

      if ($user = true)

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

      • Death Star

        I have added AppController like this..is this wrong?

  • 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

  • Cyril CHEMIN

    hello and thanks for your tutorial. I’m not an expert and i using your
    sample in a project. For some reasons, my teamate want to change the
    server and the DB for node.js and mongo.db. i’m wondering if you have a
    solution to make the same thing without SQLite ?

  • Michael Keller

    Hello everyone, I’m Michael.😊
    How do I add a new line by calling the “User Status” database inside a TextView in MainActivity?
    I’m try but don’t work anything 🙁

  • umang mehta

    Hi, I am new to android, and tried this code completely with no modification,application get crashed each time by clicking reg button on login button.

    tested php code its working great
    but android code is not working at all.

    • Have you checked the LogCat in Android Studio for errors?

  • Michael Keller

    How do I get the “user status” inside the users table database, and send it to a Textview inside the MainActivity?
    Heeelp😓

    • You need to maintain a column in users table (or create a new table called user_online_status) and insert online value when user logged in or opened app.

      • Michael Keller

        I will use this later, but I think I did not express myself very well, I would like to display in a Textview a message for example: “Hello world, this is my profile status”. But I have to get the message from each user inside a column called Status. It would look like the old whatsapp status. https://uploads.disquscdn.com/images/2b47f88c0259c72ec6bd7bf5f7bd64b0d3110f785434d8a2dc235e92818f855d.jpg

        • Okay. You need to add another column to users table called status and store user status there. Write another php endpoint to update user status. You need to have proper idea about writing php code.

          Below article gives you some idea
          https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

          • Michael Keller

            I saw the article, but I can not understand. To tell you the truth I do not know how to start. The MainActivity already takes the Name and Email of the logged in user, I just wanted to get one more that would be the Status / Citation.

          • It is all because you don’t have primary knowledge in both android and php. Hence it can’t be done. I suggest you wait for few days, learn them well and get back to this problem.

      • Death Star

        when I access it from Postman it says the same “Error True Missing input email, name, password. When I provide this, it gives me an error on line 36 in DB_FUNCTIONS

  • It seems AppController is not added to AndroidManifest.xml <application> tag.

  • Great.

  • Is the JSON is proper first of all? If you access the url from Postman, it should echo only plain json not other php errors. Pls check that first.

  • Anshul Grover

    hello sir thanks for your guidance but getting some errors please help me sir….
    i added few more values like address,phone etc and make changes everywhere in android php code related to them
    W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    also used postman for passing values getting the result below:
    {
    "error": true,
    "error_msg": "Required parameters is missing!"
    }
    pleaseeeeeeeee help me sir…………

    • It seems the JSON is not proper, there might be php errors. Check the endpoints with Postman and see if there are any php errors.

      • Anshul Grover

        by postman getting this only
        {
        “error”: true,
        “error_msg”: “Required parameters is missing!”
        }

  • Mahantesh Gurav

    It Works for me, Great tutorial, but how can i write php for forgot password?. Please help.

  • Falan Abdulla

    thanks for the post

    unfortunately im getting blank toast while register

    can you please help?

  • prashant maheshwari

    i need help, My App is not sending data back to database, when i added some more Fields. the App launches and after filling the fields, when i click register the progress bar just arrives and gone. when i had checked database then nothing is showing there.

    • You need to understand the code and modify the code in android, php and database as required.

      • prashant maheshwari

        I have done my changes as!!
        ——>>
        public function storeUser($name, $lname, $email, $password, $mobile) {
        $uuid = uniqid(”, true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash[“encrypted”];
        $salt = $hash[“salt”];

        $stmt = $this->conn->prepare(“INSERT INTO users(unique_id, name, lname, email, encrypted_password, mobile, salt, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, NOW())”);
        if (!$stmt) {
        echo “false”;
        }
        else {
        $stmt->bind_param(“sssssss”, $unique_id, $name, $lname, $email, $encrypted_password, $mobile, $salt);
        $result = $stmt->execute();
        $stmt->close();
        }

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

        but the error occured is “error”:true,”error_msg”:”Unknown error occurred in registration! in register and my register php code is—–>>>
        FALSE);

        if (isset($_POST[‘name’]) && isset($_POST[‘lname’]) && isset($_POST[’email’]) && isset($_POST[‘password’]) && isset($_POST[‘mobile’])) {

        // receiving the post params
        $name = $_POST[‘name’];
        $lname = $_POST[‘lname’];
        $email = $_POST[’email’];
        $password = $_POST[‘password’];
        $mobile = $_POST[‘mobile’];

        // 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, $lname, $email, $password, $mobile);
        if ($user) {
        // user stored successfully
        $response[“error”] = FALSE;
        $response[“uid”] = $user[“unique_id”];
        $response[“user”][“name”] = $user[“name”];
        $response[“user”][“lname”] = $user[“lname”];
        $response[“user”][“email”] = $user[“email”];
        $response[“user”][“mobile”] = $user[“mobile”];
        $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, lname, email, password, mobile) is missing!”;
        echo json_encode($response);
        }
        ?>

        Plz tell me the correct solution… plz plz.

        • You can debug using Try Catch. Try wrapping your php code in try code and see what error was thrown. Alternatively you can enable php error reporting and see the errors along with the json.

          • prashant maheshwari

            thank sir,

  • Thomas Chateau

    Hello Ravi !
    First of all, amazing tuto, really clear and helpfull 🙂
    I’m just issuing a problem that a lot of people have and I can’t fix it.
    It has been a few hours I’m trying to solve it and still, no solution for me. I’ve read all the comments and tried a few things but still the same problem …
    So let me explain :
    Your code works perfectly but when I’m registering I got a fatal error with the Json parsing.
    Catlog error :
    https://uploads.disquscdn.com/images/e22c9fe703dcb532093be041a1545d7eda1a00cc69c00c7beab5943b070695b8.png
    So the problem from what I understood come from the PHP.
    The error is :
    “{“error”:true,”error_msg”:”Required parameters email or password is missing!”}”
    So that means that nothing is sent.
    When I’m using Postman, it returns me an error with the line 36 of DB_Functions.php but it looks fine for me…
    https://uploads.disquscdn.com/images/6d2a3b8062f4290d12223b673cbf00bd92a4233c0150373388a34feec830ad64.png
    I hope your answer will help me. I’ve seen you have answered to that kind of question a lot so you must be tired…
    Again thanks for this tutorial,
    Thomas

    • Thomas Chateau

      By the way, I tried this “solution” :
      require_once dirname(__FILE__).
      And apparently it’s not from there. Still the same error with the bind_param() function.

      • Do you have mysqli enabled?

        • Thomas Chateau

          Yes, and I looked in php.ini and this line isn’t a comment (it happens for some people that the error come from there)
          extension=php_mysqli.dll

          • Yes, debugging PHP errors in pain. You can search a bit to fix them.

  • prashant maheshwari

    hi ravi sir,
    IS your GCM PHP MYSQL realtime chat APP works Without Internet??
    PLZ reply me ASAP,, plz….

    • Nope. Without Internet how the messages will be transferred.

  • Seems some fields are missing from your SQLite table. I can see address column is missing. If you have properly kept the columns names in CREATE statement, try uninstalling the app and install again as newly added columns will be created only on first time app install.

  • Gerd Marinelli

    Hi Ravi,

    I first have to thank you for sharing your deep knowledge, to spend your time for creating your tutorials and to support so many people worldwide. Really impressive! I didn’t want to disturb you and so I looked now 1,5 days for a solution to this following debugging challenge … but wasn’t able to find:

    In LoginActivity and in RegisterActivity inside checkLogin() and registerUser() we have the onResponse()-Override in which we call a Log

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

    where the .toString() gives me a fatal error while executing the app, showing me the whole register.php or login.php in the log (Logcat) and then:

    org.json.JSONException: Value register.php of type java.lang.String cannot be converted to JSONObject

    with also mentioning line:

    AppConfig.URL_LOGIN, new Response.Listener() {
    or
    AppConfig.URL_REGISTER, new Response.Listener() {

    Android Studio signs response.toString() also as redundant to the “String response”-variable definition in the onResponse()-Method.

    So when I remove the .toString() from the remove variable, I get another error:

    E/Volley: [147] BasicNetwork.performRequest: Unexpected response code 412 for http://192.168.178.108/android_login_api/register.php

    with

    E/RegisterActivity: Login Error: null

    which is keeping also when I restore the .toString() or remove the whole Log – only on new test devices I ‘m able to reproduce the first error, what could mean that Volley is getting an expression that cannot be handled … maybe because of the String definition … ???

    I first thought it would be an error in implementing your solution to my existing code, but after exactly rebuilding your solution 1:1 (even with same package name) I have the same result …

    In URL_LOGIN and URL_REGISTER I have set my IP (192.168.178.108) which I of course got from ipconfig. I’m running Wampserver64 and used the mySQL-DB, not like with my App-DB which is the MariaDB. I used the standard root login without password like in the phpMyAdmin-login and localhost as host like it is mentioned in the phpMyAdmin welcome-screen.

    Is the String definition in:

    public void onResponse(String response)

    really correct? … or where else could you expect the solution?

    It would be fine if you could find some time – if not, thank you as well for your efforts to the whole worldwide developer community.

    Best regards
    Gerd

  • Syed Abdul Rahman Wafa

    Hi sir,
    why I cannot add images using ImageView at activity_login.xml ?
    The image is not shown in the emulator.

  • Budi Purwanto

    Mr. Ravi, why with this?

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

    • Aaron Muzira S

      Add this to your manifest

      • Budi Purwanto

        thanks, work it.

  • Aaron Muzira S

    Hello Mr.Ravi i have tried to check everything even from comments tried, but still i cannot register new user into the database, below is my logcat. and i will comment my DbFunctions.php and Register.php thanks

    11-10 03:26:09.646 3519-3519/com.aaron.loghive D/RegisterActivity: Register Response:
    Fatal error: Call to a member function bind_param() on boolean in C:xampphtdocslead_testincludeDB_Functions.php on line 31
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: at org.json.JSONObject.(JSONObject.java:160)
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: at org.json.JSONObject.(JSONObject.java:173)
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: at com.aaron.loghive.activity.RegisterActivity$3.onResponse(RegisterActivity.java:131)
    11-10 03:26:09.720 3519-3519/com.aaron.loghive W/System.err: at com.aaron.loghive.activity.RegisterActivity$3.onResponse(RegisterActivity.java:123)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at android.os.Looper.loop(Looper.java:154)
    11-10 03:26:09.721 3519-3519/com.aaron.loghive W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
    11-10 03:26:09.722 3519-3519/com.aaron.loghive W/System.err: at java.lang.reflect.Method.invoke(Native Method)
    11-10 03:26:09.722 3519-3519/com.aaron.loghive W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    11-10 03:26:09.722 3519-3519/com.aaron.loghive W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

    • Check your json url from Postman, seems there are php errors printing along with json.

  • Izzul Islam

    Hello Mr. Ravi please help me for this eror
    Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
    > java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

    • Clean the project from Android Studio (Build -> Clean) and try again. If the problem still exists add the MultiDex support to your project.

      https://developer.android.com/studio/build/multidex.html

      • Izzul Islam

        Still same Mr ??

        • Pls paste your gradle code after adding mutlidex support.

          • Izzul Islam

            what is the meaning of tools:context=”${relativePackage}.${activityClass}” script in the activity main ?

  • Techlingda Tutorials

    how to remove encrypted password

    • Could you explain a bit your query.

      • Techlingda Tutorials

        I means that when I enter password,email and full name password saves as a different way in users database.So how to solve that

        • Passwords are encrypted for security purpose. Even somebody got access to your database (let’s say hacked), they can’t see the password and login into others accounts.

  • Preeti Karekar

    Hello Ravi,
    I am getting Volly error saying null as error response while registering…

    Here is my logcat

    W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
    D/NetworkSecurityConfig: No Network Security Config specified, using platform default
    E/Volley: [4277] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.43.66/android_login_api/register.php
    E/Volley: [4277] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.43.66/android_login_api/register.php
    E/RegisterActivity: Registration Error: null

  • Techlingda Tutorials

    I tried your this and it works perfectly.Then I host android_api in a server.After that I make a database which is called carbon12_android_api.But after changing that name It never work register or login
    PLEASE HELP ME

  • You need to enable mysqli extension on server / MAMP.

    • Techlingda Tutorials

      can you tell me how to activate it in hostgator. I tried but they become failure

      • You need to check whether Hostgator provides that option. Contact the support team.

  • Selene Malosso

    Hi guys,
    I’m getting this error no matter what I do, can someone please help?

    11-18 12:38:56.168 3907-3907/com.example.administrator.loginandroidapi E/RegisterActivity: Registration Error: javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0x91498bc0: I/O error during system call, Connection reset by peer

    • Which device you are testing it on? Is the url https?

      • Selene Malosso

        I’ve tried on my Samsung Galaxy s7, on the virtual devices of Android Studio ( Nexus 5 and Nexus 5X) and on a Zopo one.
        I’m not using Wamp but the IP of my own domain and i’ve tried both http and https!
        Thank you for helping me 🙂

        • Ok. Is the urls accessible via Postman?

          • Selene Malosso

            How can I know that?

          • Selene Malosso

            I’ve just seen the other answer, I try and I let you know 🙂

          • Selene Malosso

            Solved! Everything works now! There was a problem with the andress! Thank you so much 🙂

          • Awesome 🙂

  • Bijay Luitel

    Hi Ravi, whenever I try to register and provide full name, email and password, and click on register, the app stops automatically. Could you please tell me what could be the issue?

  • Seems you have missed out 8th point in android section.


    <application
    android:name="info.androidhive.loginandregistration.app.AppController"

    • Bijay Luitel

      I missed the code https://uploads.disquscdn.com/images/76ac48d1cec8be3826d1374542618316a751656c8ce9455a80bd32ccaeaf9652.png , so I copied the above code and made some changes. But still getting error, can you please tell me what might be the reason for error.

      • Replace @drawable with @mipmap

        • Bijay Luitel

          Thank you very much Ravi. App is not stopping now, but I can’t register a user. It gives me following error in log cat and I can’t see any user in my database. https://uploads.disquscdn.com/images/fca22ac33ea41815edf50a59f8885777ec7c846d63abd847561f3490db265b9c.png

          • Hi Bijay

            Pls spend time on understanding the article and codes. I would like to answer to your queries only tomorrow.

          • Bijay Luitel

            I will do that and will let you know tomorrow, if I can’t come up with an answer. Thank you very much! Also, I have sent you a friend request and a text message on facebook. It would be great, if I can be on your friendlist and can learn many things from you. Thank you very much Ravi!

          • Bijay Luitel

            Registration error: Null, I’m getting this error in cat log.

          • Bijay Luitel

            Please ignore my message. Got the solution.

          • Bijay Luitel

            The issue was because of IP address.

          • Bijay Luitel

            Hi Ravi,

            I still couldn’t find the above solution. Are you able to help me please?

    • Bijay Luitel

      Says cannot resolve symbol

  • Pippy O Lewiso

    Hi Ravi, I am receiving this error in the logcat ‘E/MultiWindowProxy: getServiceInstance failed’ then ‘E/RegisterActivity: Registration Error: null’ when i am trying to register

    • Seems the url is not accessible via device / emulator.

  • Amitpal Singh

    Hey ravi thanks for helping out noobs here 🙂
    i created new activities where user entered their blood group and phone with name after logged in .
    Android part is quite done i have created sqllitehandler2 with new postReqActivity changed the values but the problem is logcat is giving me error please check the screenshot attached secondly i have added new PHP file for this activity and added link to that on app config and changed the variable on both plus added new function on DB_Func file but my logcat is not happy please check the screenshot , Thanks for help https://uploads.disquscdn.com/images/f8c6a1ad042736a57514432d7597fccc7ceecef4ce6feac9636b4ecc18fe14e4.png

  • Anas

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

    Getting this error when ever trying to params for testing,
    tried on wamp,xampp,hosted website but getting same error everywhere,
    Please help me

    • Are you using Postman to test? This uses a POST method which can’t be send via website.

    • Brian Lun

      You can try it with POSTMAN and remember to put your params in Body but not Headers

  • Brian Lun

    You should not perform db.adduser in RegisterActivity. Otherwise if you signup an account and login with another one, the MainActivity will show the previous one. adding user into sqlite in LoginActivity is already enough.

    • Brian Lun

      But this is a very good tutorial indeed. It really helped me. Thank you Ravi.

      • You are welcome and thanks for replying to others 🙂

  • Riley

    Getting this error:

    android.database.sqlite.SQLiteException: no such table: users (code 1): , while compiling: DELETE FROM users

  • Kallanar

    i did as you directed and created android_login_api in the www directory i keep getting this error

    The requested URL /android_login_api/register.php was not found on this server.

    i am using an AWS EC2 server and i went into command line and the android_login_api is there in www.

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

    • I think on Server, the files go into html folder not just www.

      The path will be /var/www/html/android_login_api. Try this once.

  • Bijay Luitel

    Hi Ravi, If I need to allow user to store atleast 6 digit password with combination of number and letter and also have them enter only valid email address in order to register then where can I add a code? Please let me know and what code, if you can please,

  • vips

    hii ravi, first of all nice tutorial man,here i just need your help actually i have build every files and folders like yours and i have also made necessary changes like changing the database name, table name where necessary but every time i am trying to access the api by using url it says like ‘{“error”:true,”error_msg”:”Required parameters email or password is missing!”}’ and same with both register and login api and i have also checked the code on postman but the situation remains unchanged and same error is still there ,so please help with it

    • vips

      i enabled mysqli in php.ini file and got it working through postman but still the android part does not seem to be working correctly, actually nothing happens whenever i write credentials on android edittext i think it is not able to connect to local database

      • The local database can’t be connected via android mobile. For that you need to use ip address of your computer and both the devices has to be in the same wifi network.

        What is the url you are using to connected from android?

    • vips

      it is working all fine now as i have uploaded it on real servers

  • Brian Lun

    Hi Ravi, I am actually new to Android Development. I would like to ask you if it is possible to use session manager to store some data that has to be shared to different intent, then I don’t need to pass it via putExtra. Is it possible?

  • Chong Jeng Song
    • You have PHP errors. Hit the same url from Postman, you can see the php errors there. Try to fix them until you get proper json response. (enable php error reporting if you are not seeing errors in Postman)

  • Haris Bashir

    Help me to solve this problem i see every thing in logcat but problem not solved

    • Can u post the error from LogCat here?

      • Haris Bashir

        thnx but this error was resolved

  • Fj Why

    Thank
    you in advance, I tried your code, and had a bit of trouble on login,
    did not display any error on toast, and did not go into MainActivity,
    even though all inputs are correct. I have not modified anything in your script. what’s the problem?

    thanks Ravi

    • Have read the last section 5. Testing the App ?

      • Fj Why

        Yess Ravi, when I register, everything runs correctly, and the data I input has also entered into the database, but when I login with the correct data, it does not go into MainActivity, and just show the empty toast

        thanks in advanced…

        • Is the registration happened via android app?

          • Fj Why

            Yes Ravi… and that’s no problem

          • Have you checked the LogCat for any errors. Also hit the login url from Postman and see whats happening?

  • La Messi

    Hi very nice tutorial i can’t make it work when i try to login its crush unless i commented out

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req); on line 192
    if i did this the spin non stop please help

    • Seems AppController is not added to manifest file. Recheck the 8th point.

  • vips

    hello , i need help in login problem of my app ,the scene is like when i tried same code of both php and android and localhost wamp as my server ,it worked all fine but as soon as i posted that same files to actual hostinger servers ,there are some problems, the register however is working and it stores data but the login function does not seem to work whenever i try to login with credentials , there is a error toast as ‘ Value <br of type java.lang.String cannot be converted to JSONObject on android ' , then i searched on internet but not able to solve it fully so please help me…

  • vips

    hello , i need help in login problem of my app ,the scene is like when i tried same code of both php and android and localhost wamp as my server ,it worked all fine but as soon as i posted that same files to actual hostinger servers ,there are some problems, the register however is working and it stores data but the login function does not seem to work whenever i try to login with credentials , there is a error toast as “Value <br of type java.lang.String cannot be converted to JSONObject" , i searched on internet also but with no success..

  • Jenny Gutiérrez

    Why do you use SQLite if you have MYSQL?

  • Chandu Parmar

    Hey Ravi,This works perfectly! Thank you
    Registration is working but I have a problem in login
    Activity: Login Response:
    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/u962968717/public_html/android_login_api/DB_Functions.php on line 64

    I copied you exact code but it is showing me error

    • You need to enable mysqli extension in your php.

  • grinaldi FOc

    i have problem when i have success on login, it’s crash when the app want to load mainActivity. please help me https://uploads.disquscdn.com/images/3e4b71adacc279752b9f3193b21ba1315414681a7d4e6176ddd3414a951faccf.png

    • Pls post the xml code of your main activity.

  • Osaim Jaan

    How the files are upload on wamp server the data base is not attached i copied all the data base file Android_login_api , Those file you uploded and that is not working how the database are attached ?

  • Michael Keller

    Why is it so complicated to create a String to display only a “surname”? I’ve tried it in many ways, but I can’t! Please, help me, I’m already discouraged by this. 🙁 https://uploads.disquscdn.com/images/26a1ccfd96b23ac1dac55ac2664751b637907b572e7c86592a5dfc1823d7a69e.png

    • What are the ways you have tried?

      • Michael Keller

        I’ve tried in several ways how to create a String KEY inside the SQLiteHandler, inside the MainActivity, LoginActivity and RegisterActivity and also inside the DB_Functions to see if I could get some connection, but I can’t. 🙁

      • Michael Keller

        I just need a text from within the users/surname and display in a textview. But I can’t.

        • Have you able to display any other information like email or name?

          • Michael Keller

            Yes, the email and name are working perfectly, but I can not display anything else besides them.

  • erick jayson deguzman

    Sir Ravi Tamada, Wheres my error in my code ?
    and how to fix the tools in activity_main.xml tools:context=”${relativePackage}.${activityClass}”
    and i dont know how to get value of android to get phpmyadmin

    https://uploads.disquscdn.com/images/d55c96c8e54689292b0f13970672830484c91f1bd104de5a09b4186f182d5bda.jpg

  • erick jayson deguzman
  • PATRICK MUNYENSANGA

    Hello Ravi,i used your code but i cant register because the App is Unfortunately has stopped; i have used XAMPP for my MSQGL and phpMyAdmin/
    how can i solve this problem

    • You can find the error in LogCat of Android Studio when the app crashes.

  • Arga Milo

    Hey i have some error in android studio, i hope you can solve this..
    D/RegisterActivity: Login Response: {“error”:true,”error_msg”:”Required parameters email or password is missing!”}

  • Hello Sir!
    I am trying to run API but getting below response everytime I click on Send in Post Man:
    {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}
    Seems like isset function in register.php is getting null.
    I have tried to run on Post Man but couldn’t succeed. Below is the screenshot.
    Please help!
    https://uploads.disquscdn.com/images/05223c3521845b6180b39031dd38c9e1f8735873cb9b295d3b3bc8b2bc7ad879.png

  • erick jayson deguzman

    i want to attach my program to my phone, and url is still the same 10.0.2.2?

  • Isat Mos

    What the happen?
    *********************
    Error:Unsupported method: BaseConfig.getApplicationIdSuffix().
    The version of Gradle you connect to does not support that method.
    To resolve the problem you can change/upgrade the target version of Gradle you connect to.
    Alternatively, you can ignore this exception and read other information from the model.
    *********************
    Help me! Thank you

  • Jobin Jeeji

    the url in the appconfig is not working

    • You have to modify it according to your machine ip address when you are in a wifi network.

  • The LogCat should print the line number and file name also.

  • Rafael

    For all struggling with:
    org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

    open your Condig.php file in wamp directory and modify DB_PASSWORD by removing it (leave empty pranthesis"" like below):
    define("DB_PASSWORD", "");

    All other problems:
    1. AppConfig: make sure to check your local ip (disable firewall) and put in URL_LOGIN and URL_REGISTER
    2. Manisfest.xml: add android:name="yourappsname.AppController"
    3. Manifest.xml: add internet permission:
    4. Manifest: add Register and Login activities like this:

    5. All java files: modify import statements by changings its name to your apps name.

    The app is working as of 19.12.2017.
    Thanks again Ravi for all your tutorials. Much appreciated!

  • Rafael

    For all struggling with:

    org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

    modify your Config.php anch remove password by leaving empty parenthesis like this:
    define("DB_PASSWORD", "");

  • Praful Dhabekar

    Hi Ravi, I’m getting following error. Can you please tell what I did wrong.?

    https://uploads.disquscdn.com/images/17a49f130bf12ed414c9b7e28df85d6137a259ff3dfe243e6ea24a0509a7c88c.png

    • Praful Dhabekar

      Hi, somehow I resolved the issue but stuck with another one, I’m unable to insert data into MySQL database, and yes my phone and laptop are connected to same network.
      Please help.

      • Whats the problem with mysql insertion. Explain the scenario / code would be useful.

        • Praful Dhabekar

          Hi again, I resolved the issue. The problem was with my WiFi Firewall setting I had to turn it off . Thanks for you response and for your tutorial also. Maybe it’s too much to ask but do you have any tutorial on Filter JSON Data in Android Application using PHP and MySQL?

          • Yeah figuring out the Wifi problem is tricky always, it’s good that you figured it out. I haven’t done any filtering article as of now. You can just create an endpoint and write the php logic to search by LIKE statement in mysql and return the response. If the data is very less (below 100 rows), you can use client side filtering to show the same.

            https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/

          • Praful Dhabekar

            Thank you for your reply. Looking forward to learn more great tutorials.
            Peace ✌️

          • Yes, I am working on it 🙂

  • Mansi Ratanghayra

    Hello Sir, this code runs fine in case I store in localhost..but when I store in hostinger server then I get the following error :
    Call to undefined method mysqli_stmt::get_result()
    Please help me getting me out of this..

    • You need to enable mysqli extension on your hosting server.

  • Amit Saxena

    https://uploads.disquscdn.com/images/c8c61c4b6b4ef1d3625ec184402fa5f692bfd68dacd17a1c31e38018e7fc4464.png
    Hello Ravi, Thanks for this tutorial….I have a problem….My App registration page is working fine and user is registering in the database but when i i am login with same credentials in login screen…it is not working…i am getting the json error…i am not updated any code…i am attaching the screenshot of my app and logcat…plz help me

  • vikash

    how to add forget password

  • Kristian Cardona

    https://uploads.disquscdn.com/images/c710e70c1d9b29474d07a2926a9a49cd7e844d47bfbde50b2a90f667d13fbfbf.jpg

    Hi Ravi, I’m trying out your code but when I try to register or login the app crashes with this log

  • Mark

    Hi Ravi, thanks for posting this by the way, how can this be modified to use/create wordpress user accounts?
    Thanks,
    Mark

  • hariharakumar

    that is his own package structure…..download the source code and find that file in his code. or….just dont write that line.

  • hari hara kumar

    Hi ravi,
    I am facing Server Error in register activity. Please help me!

    • Check the php error logs or use Postman to make call to same url to see the php errors.

  • Vishist Varugeese

    Hello Ravi Sir.
    I am new to android development. From what I have read on Google, SQLite is a database that is server-less and is locally available in Android. So in this article”Android Login and Registration with PHP, MySQL and SQLite” is it okay if i skip the SQLite part? What would be the drawbacks of doing so? Please help me clarify my doubt.

    • Hi Vishist

      We used SQLite here just to cache / offline data. Let’s say you want to display some profile information like email, name, address etc., we can store this info SQlite, so that even if there is no internet connection we can show the data. Otherwise we need to fetch this information by making call to server everytime. It’s completely upto you whether to consider it or not.

  • Erickson Teixeira

    Hi Sir
    Please help me
    I followed your steps and the app returns this message: json error value <br of type java lang string cannot be converted to json object
    Could you guide me?

    • Erickson Teixeira

      and there’s no error in logcat

      • You need to hit the url from Postman by passing correct params. You can see the php errors if there are any. Seems the json returned not proper, it might contain php errors / warnings.

  • Fariha Reza

    I have just started to learn android app development recently! Thank you so much for this tutorial!!! It’s so easy to understand! Thank you very much! 🙂

  • Jdn90

    Hello Ravi,

    Nice to see that you are still responding regarding this. I am having issues with this as I’ve spent a few days trying to figure out what I’m missing. I’ve created the application, added the table to phpmyadmin and also know my ip address for my computer that I’m trying to use as the server. The issue I’m having is sending the response to the phpmyadmin as when I try to register a circular toast icon appears with no words and doesn’t add users to the table. I’m also not sure where I’m supposed to put the JSON responses? Also in both the Register and Login activity I am getting an error at public void onResponse onErrorResponse and StringRequest saying that the class doesn’t override its superclass. I’m not entirely new at development but don’t understand the php mysql stuff yet and need to learn it by the new year.
    Thank you if you responde

    • Hi

      First of all, you need to make sure that the JSON endpoints are working fine. For this use Postman client to test the URLs and make sure the JSON response is proper. Once that is done, the URLs should be accessible via mobile. The mobile and PC should be on the same network. Open the same URL directly in the mobile browser to see whether it’s accessible via wifi network.

      Please post your complete error log for further debuggin.

      Thanks for your appreciation 🙂

      • Jdn90

        Hello Ravi,

        I have checked into this and downloaded Postman. What I get when I load the URL in Postman is the following {“error”:true,”error_msg”:”Required parameters email or password is missing!”}–{“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}– If this is correct than I’m definitely doing something wrong with being able to access the URL’s from my device. When I load them via Chrome on my computer they show the same message, but when I load the URL from my phone same WiFi (I did follow steps) it won’t grab the information.

        Hope I can get some insight on this more,
        Thank you!

        • Then the device IP is not available through your mobile. Troubleshoot https://www.techadvisor.co.uk/how-to/network-wifi/how-connect-router-3633777/

          • Jdn90

            Hello Ravi,

            I have tried everything possible to access other devices on my network with both the routers I have plus even my range extender. I’ve also even hard wired my computers and tried accessing other computers from both routers separate and still not able to access the files unless on the main computer running postman. So I’m unsure as to what is happening here.

            Thanks again.

          • Okay.

            1. What your localhost URL and the URL with your PC IP address you are trying to open in the mobile browser?

            2. If the problem still persists, you can get another spare mobile and create a hotspot. Connect your mobile and PC to this hotspot and try. (Creating the hotspot from the same mobile on which you are trying the app won’t work)

  • Anand Vb

    This is a great tutorial, very much helpful.
    Hi, i like to dig deep into android, can you help me out?. How to connect with you?

    • I think reading all the articles on the blog would be sufficient to get decent knowledge 🙂

      • Anand Vb

        I am Always here from the beginning of my android learning, i will definetly read all articles

        • Great. For more information buy any Video series also from Udemy or Udacity.

  • Kristian Cardona

    I am getting java.net.SocketException: Permission Denied

    • Kristian Cardona

      Solved, didn’t include INTERNET permission into manifest

  • Vishist Varugeese

    In LoginActivity, what does this function getParams() do? Is it sending the parameters to the SQLite database or to the PHP scripts?
    https://uploads.disquscdn.com/images/d0a7e62e8d202e3ac054fe29371dc7336065cd1d753d8e42b2044de073142179.jpg

    • It sends it to PHP server. SQLite plays no role here.

  • Philip Lartey

    Hi Ravi, Thanks for the wonderful tutorials. Is it possible to do another tutorial using JWT instead for below code for encoding and decoding..

    /**
    * 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;
    }

    I believe that the new way to go for encryption

    • Hi Philip

      This is just a beginner article. Once you got an idea, try using any PHP framework like Slim or Laravel for better API and security.

  • Reza oktovian

    if using xampp is the same?

    • Yes, the only difference would be the port number of localhost running on.

      • Reza oktovian

        oke thanks, its work 🙂 .

  • Gohil Khengar

    in program Registration SuccessFully But When Login page can not load data from database…..

    • Hit the login url from Postman and see what response you are getting. It should be proper json, shouldn’t have any php errors printed.

  • Kunal

    I try to use your code but i get the error on AppConfig, How to resolve this problem? I import the AppConfig but its showing error

    • What is the error?

      • Kunal

        I apply your code in my project and run in the emulator but its not shown any error and its accept wrong email id also.

        • You can find any error / info in LogCat of Android Studio.

    • Gohil Khengar

      android:name=”.app.AppController” Add This line in Menifest File

  • King

    Hello. Thanks for the great tutorial. I have successfully built the apk file. I tested it in my mobile phone and I faced a problem. Whenever I entered all the information and then clicked the button of login or register, the application will be terminated immediately. I even don’t know what the problem is. Do you have any idea what problem I am facing and how to solve it. Thank you!

    • Connect your phone to your PC via USB cable and install the app from Android Studio. You can see the errors in LogCat of Android Studio when the app is crashed.

      • King

        Thank you very much! It seem like the error is “01-04 02:25:39.096 417-417/? E/Parcel: Reading a NULL string not supported here.”
        However, I have entered the required information to the fields.
        What is the problem? (cry)

  • erick jayson deguzman
    • You need to replace the IP address with your web url. Also it depends on where you put the files on the server. andorid_login_api might change. You can verify your urls by accessing them via PostMan.

      • erick jayson deguzman

        i input like this ?

        =”http//Account IP/name of db in phpmyadmin/folder/php file”???

      • erick jayson deguzman

        i input like this ?

        =”http//Account IP/name of db in phpmyadmin/folder/php file”???

  • The error is there at LoginActivity.java line number 186. The variable or something not initialized. Paste the code of you LoginActivity around #186 lines.

    • King

      Here is the codes from line 107 to line 187.

      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,
      LoginMainActivity.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);
      }

      • Have you added AppController to AndroidManifest.xml?

        Mentioned in 8th point in the same article.

        • King

          Thank you, Sir!!! The problem is solved. Thank you for the quick response!!

  • Kunal

    Hi Ravi, I am using your code for my login signup but when i run the program its shows data successful enter but in my server there is no data and when i login from that username its shows. please provide me your mail id so i can mail you my problem

  • Kunal

    This error i got this from this code (“Value null of type org.json.JSONObject$1 cannot be converted to JSONObject”) in this specific line showing the error JSONObject jObj = new JSONObject(response);
    and
    StringRequest strReq = new StringRequest(Request.Method.POST,
    AppConfig.URL_REGISTER, new Response.Listener() {

    • You need to check Null on response value before converting it into JSONObject.

      if(response == null){
      // unable get response
      return;
      }

      // your normal code here

      • Kunal

        I don’t understand

        • I mean to say check whether response is null or not before converting it to JSONObject.

          • Kunal

            Its showing null

  • erick jayson deguzman

    Hi Ravi , im trying to postman . it works but
    android cant request to website. im using laravel for site. i think there’s a problem.
    i dont know what can i input from url login and register. Tnx
    https://uploads.disquscdn.com/images/d367a5a3babf42d2f6a5ff1208787f1526297ec54b276c7d46a40e2397771bde.png

    • There is a PHP error. Check your Laravel’s error logs.

  • pratibha

    Hi im getting the error in POST >can’t find symbol variable POST
    what should i do please as soon as possible

  • Jay Prakash Sah

    how to retrieve all the user id name and email id from firebase in admin login

  • erick jayson deguzman

    Good day Sir Ravi, we are using GET in Postman. it works . i can log in . but in Android . String request
    i will change Method Post to GET?

    https://uploads.disquscdn.com/images/55ec4ea49f0b6bf598b32ff664ab5776d64f79cf7b44c12c6897d963d1df5fc9.png

  • erick jayson deguzman

    Good Day SIR Ravi, is there way to insert crf token in my post request? that laravel required?

  • erick jayson deguzman

    Good day Sir Ravi. do you know how to convert url like token to avoid because my url was revealed. the user/programmer will see the account information . i want to hide it . TIA
    https://uploads.disquscdn.com/images/3ff9431d62df23f42b11aa9a95b3f783ed113e4c8d1d2658e40015d83d3ec962.png

  • IK

    please let me what is the this file info.androidhive.loginandregistration.R; is it constants files. i cant able to see in u r source.

    please help me on this…

    • It will be generated automatically once the project is built. It has to match with your package name.

  • Bob

    I have completed the application but I have one question. How to enable the action bar? When I completed the project, the action bar of the application is disappeared in my phone but I can still see the action bar in the design of layout file. I want to enable the action bar. Thank you.

    • You can enable action bar by adding the AppBar in your xml layout or use the theme in AndroidManifest.xml

      In this article, the AppBar is added to xml layout
      https://www.androidhive.info/2017/12/android-working-with-bottom-sheet/

      • Bob

        When I added an additional action bar, it give me an error like:This Activity already has an action bar supplied by the……
        In fact, I can see my action bar in the layout.xml file. However, when I executed the application, the action bar was disappeared. I compared the manifest file of this application to the newly created application. They do not contain a big difference but the newly created application contain the action bar. I really wonder how I can make the action bar appear again.

  • Adedokun Adekola
    • You can 500 Internal Server Error in the screenshot. Check you hosting error logs.

  • joo

    Hello i followed all of ur tutorials but im having trouble registering. it seems like data is not going in….can you help me with this plz? thank you! https://uploads.disquscdn.com/images/8ce595aa2354b5b5a8cf2bc2f33f32fa2d9e0eab730b2be02d58495516ccaa0f.png

  • joo

    https://uploads.disquscdn.com/images/ffa8c85a02887c5913e259f1215e675d49ae2065e3129dc45469c550c268daee.png
    hello i’m having trouble dealing with type dismatch in the lines 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();

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

    can you plz help me with this?

  • Cedie

    Hello. I already copied your code exactly both in Android (Android Studio) and PHP (Netbeans), as well as the database (I’m using XAMPP). Everytime I finish filling-up the registration form, all the data that I inputted in the registration form were not being stored at the localhost.

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

    Thank you!

    • Cedie

      This is the output everytime I finish filling-up the registration form:

      https://uploads.disquscdn.com/images/5298903bb5c1c4d49d6cc1d8491ee03a500ddd6e4d5268cc5409687b6d0be230.png

      • Post the code that submits this form.

        • Cedie

          This is the code:

          private void registerUser(final String name, final String email, final String password) {
          String tag_string_req = “req_register”;
          pDialog.setMessage(“Registering…”);
          showDialog();

          StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener() {
          @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) {
          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”);

          db.addUser(name, email, uid, created_at);

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

          Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
          startActivity(intent);
          finish();
          } else {
          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 getParams() {
          Map params = new HashMap();
          params.put(“name”, name);
          params.put(“email”, email);
          params.put(“password”, password);
          return params;
          }
          };
          AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
          }

          • Can Log the params variable before return statement and see if they are actually sending.

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

            Log.e(TAG, “params:” + params);
            return params;

          • Cedie

            @ravi8x:disqus Same output. 🙁

          • You haven’t gave me the printed Log in the code I have given.

            Log.e(TAG, “params:” + params);

  • TechVid VJ

    can i use same in Xampp

  • Umang Jain

    sir i downloaded the code and able to run it correctly on emulator but I am not able to run it on real device(redmi note 4).Everytime I finish filling-up the registration form, all the data that I inputted in the registration form were not being stored at the localhost. https://uploads.disquscdn.com/images/7352d0215c52dd4d391ae4d57f98a2bed00fa66765121fa71d40660eae55d27b.jpg

  • Dhawal Shukal

    https://uploads.disquscdn.com/images/0dfea40cc7ae25a0348e324faf21c77ce6d983d8a77783aaa0bae3efa43858d4.png

    Problem

    1. Once i try to Registration it successfully store data in db
    but stay on registration screen then i manually move login screen
    2. Try to login it give me

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

    i got from postman

    solution i tried
    1. http://localhost/android_login_api/login.php?name=Test&email=test@gmail.com&password=test123
    2. {
    “error”: false,
    “id”:”8″,
    “uid”: “5a56a64934f9e5.49278554”,
    “user”: {
    “name”: “Test”,
    “email”: “test@gmail.com”,
    “created_at”: “2018-01-10 18:48:25”,
    “updated_at”: null
    }
    }
    3. add right IP also
    4. if you want i can give u Log.e(TAG, “params:” + params); value

    // 01-11 14:48:01.910 8885-8941/info.androidhive.loginandregistration E/RegisterActivity: This is the value of params:{password=test123, email=test@gmail.com} //

    • There is an additional character w printed in json. Check your PHP code, there might be an accidental character left somewhere.

  • Lansana Sangare

    Hello ravi tamada,
    I think the tutorial is very good.
    I have a problem for 2 weeks now.
    I have on my windows computer a ubuntu 16.04 operating system installed on it. When I try to register, I land directly on the else loop, even though I enter the test parameter at advanced rest client. But if I initialize the parameters earlier then they will end up in the database phpmyadmin. I’m desperate, do not remember if it’s code or configuration. The code worked with wamp-server on windows, now I have Lamp-Server on Ubuntu. If you have such ideas, I would be very grateful. here is a cut-up of the code and output at advanced rest client and on the browser. https://uploads.disquscdn.com/images/86231868110697418d8d06b4946e19ddc234c8da62dcba82a273bb9f86596fbe.jpg https://uploads.disquscdn.com/images/e5dc7f403c595a67041c359d6341419efe970f17fb4b77fc6460234538668547.jpg https://uploads.disquscdn.com/images/720c9bda85892bffc11f25aff068b584581890b32246d276cec6c63633722540.jpg https://uploads.disquscdn.com/images/01f637070fb3cc9ad36d9b57596af77948375f0a8092b4d36516b71630e6884d.jpg

  • Lansana Sangare

    My php code lands directly in else loop after execution.

    I am using a static ip address from the uni on Ubuntu 16.04

    Windows.

    It leads to both the Advanced rest client and the android studio

    same issue comes out

    What could be the reason ? is about code php or configuration

  • jtaco263

    i have an issue when after login/failed login i logout and relogin keeps the login info from the first time example
    i log with user abc and pass xyz and login well then i logout and try to login with user def and pass wer and still logs like user abc? this alsdo happens if the fisrt time login credtians are wrong i cant login

    i used this: params.put(“email”, email);
    params.put(“password”, password);

    Log.e(TAG, “params:” + params);
    return params;

    but still the same problem
    now i have facebook connect whichs works perfect but my question is if String tag_string_req = “req_login”; affects on login

    here is my logcat:

    first time login :

    01-19 03:57:30.844 14955-14955/com.dattasolutions.imageupload I/RegisterActivity: datos enviados: jtaco2631q2w3e
    01-19 03:57:30.864 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{f6a9abe V.E…… R…..I. 0,0-0,0}
    01-19 03:57:30.874 14955-15401/com.dattasolutions.imageupload E/RegisterActivity: paramis:{email=jtaco263, password=1q2w3e}
    01-19 03:57:30.874 14955-15401/com.dattasolutions.imageupload I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    01-19 03:57:30.874 14955-15401/com.dattasolutions.imageupload I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    01-19 03:57:30.874 14955-15401/com.dattasolutions.imageupload I/qtaguid: Tagging socket 47 with tag bd9bffbf00000000{3181117375,0} uid -1, pid: 14955, getuid(): 10358
    01-19 03:57:30.934 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 – 0, 0) vi=Rect(0, 0 – 0, 0) or=1
    01-19 03:57:31.804 14955-15401/com.dattasolutions.imageupload I/qtaguid: Untagging socket 47
    01-19 03:57:31.834 14955-14955/com.dattasolutions.imageupload D/RegisterActivity: Login Response: {“error”:false,”uid”:48,”user”:{“name”:”jtaco263″,”email”:”jtaco263@datta.cloud”,”created_at”:”1516355852″,”updated_at”:null}}
    01-19 03:57:31.834 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: #3 mView = null
    01-19 03:57:31.864 14955-14955/com.dattasolutions.imageupload D/SessionManager: User login session modified!
    01-19 03:57:31.874 14955-14955/com.dattasolutions.imageupload D/SQLiteHandler: New user inserted into sqlite: 1

    the next logins (which still login the same person):

    01-19 03:58:16.644 14955-14955/com.dattasolutions.imageupload I/RegisterActivity: datos enviados: jfjnc
    01-19 03:58:16.664 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{1a632c1 V.E…… R…..I. 0,0-0,0}
    01-19 03:58:16.704 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 – 0, 0) vi=Rect(0, 0 – 0, 0) or=1
    01-19 03:58:16.704 14955-14955/com.dattasolutions.imageupload D/RegisterActivity: Login Response: {“error”:false,”uid”:48,”user”:{“name”:”jtaco263″,”email”:”jtaco263@datta.cloud”,”created_at”:”1516355852″,”updated_at”:null}}
    01-19 03:58:16.704 14955-14955/com.dattasolutions.imageupload D/ViewRootImpl: #3 mView = null
    01-19 03:58:16.724 14955-14955/com.dattasolutions.imageupload D/SessionManager: User login session modified!
    01-19 03:58:16.734 14955-14955/com.dattasolutions.imageupload D/SQLiteHandler: New user inserted into sqlite: 1
    01-19 03:58:16.734 14955-14955/com.dattasolutions.imageupload I/Timeline: Timeline: Activity_launch_request id:com.dattasolutions.imageupload time:392400027
    01-19 03:58:16.754 14955-14955/com.dattasolutions.imageupload E/ViewRootImpl: sendUserActionEvent() mView == null
    01-19 03:58:16.784 14955-14955/com.dattasolutions.imageupload W/ResourcesManager: getTopLevelResources: /data/app/com.dattasolutions.imageupload-1/base.apk / 1.0 running in com.dattasolutions.imageupload rsrc of package null
    01-19 03:58:16.814 14955-14955/com.dattasolutions.imageupload D/SQLiteHandler: Fetching user from Sqlite: {email=jtaco263@datta.cloud, name=jtaco263, created_at=1516355852, uid=48}

    if you see the second time doesnt appears this line:
    01-19 03:57:30.874 14955-15401/com.dattasolutions.imageupload E/RegisterActivity: paramis:{email=jtaco263, password=1q2w3e}

    how can i solve it?

  • Hansel Junio Bugwat
    • This url works with POST method. When you open it in browser, it makes GET request instead of POST. Use Postman client to send POST request with required parameters. It will work.

  • caviru

    I build the project but anytime i try to login or register unfortunately, it has stopped working

  • kabiru

    I build the project but anytime i try to login or register unfortunately, it has stopped working

    • Check your LogCat for errors.

      • kabiru

        Thank you problem solved

  • Post your SQLiteHandler.java too. Use gist to upload code.
    https://gist.github.com/

  • Kawsar Fazal

    Hi brother, I need an App like this but some other feature will be added. Please tell me how do you can help me. By developing? Or by referring a trusted Developer?
    Mail: limon.jfl@gmail.com
    Wapp: +8801745656549

  • kabiru

    sir i am trying to add more user detail eg. username, phone number, location.
    i add the them (parameters) code to both android code and the server(php) side but not working.
    if i click on register it will only load for a moment and do nothing, and i check the database it insert nothing
    https://uploads.disquscdn.com/images/562c111913eb8d0e540f6d159d7d204d3d990f20460bf5f16e7b61ba9430654d.png

  • Tsoom

    Hi

    How i can get all online users on the web service?. Is it possible?

  • Rahul Saxena SAXENA

    Warning: mysqli_connect(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:xampphtdocsandroid_login_apiincludeDB_Connect.php on line 14

    Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:xampphtdocsandroid_login_apiincludeDB_Connect.php on line 16
    {“error”:true,”error_msg”:”Required parameters email or password is missing!”}

    Hi sir,
    how to resolve this problem in postman

  • Ori Zehavi

    Hi ravi, I followed your article, and when i try to test it (the register) I get the following error:
    http://prntscr.com/i6ckcy
    I’ve entered all the variables and changed it to POST, so it should get into the registration, but instead it fails getting them.
    Any idea why it could happen?
    I’m pretty new to this WAMP server thing, this would really help me, thanks in advance <3

    • Ori Zehavi

      @ravi8x:disqus I really cant make that work, would really appreciate some help

      • I am not sure about Arc client. Have you tired using Postman?

  • Adedokun Adekola

    i am having issue with the registration code after i have upload it to digitalocean Ubuntu server pls help me out
    this is the error
    ({“error”:true,”error_msg”:”Unknown error occurred in registration!”})

    https://uploads.disquscdn.com/images/5feb562390472cbb4c7c4b567227f56813c70af91e4ba235d72a8182df77c287.png

    • Check your server logs. Possibly the error log will be at /var/log/_YOUR_SERVER_NAME_ (_YOUR_SERVER_NAME_ can be nginx or apache2 depending on server stack).

      • Adedokun Adekola

        pls sir i will happy if you explain more for me because i dont understand this

        • Okay. Normally there would be php / mysql errors when you are deploying services on server. It’s because of may few extensions might not enable in php. To see the errors you need to open the error logs on the server and see the errors.

          For example, if the server I am using is Nginx, the error logs can be at /var/log/nginx/errors.log. If you open this file via terminal / FTP you can see the errors. By going through the errors and searching for the solution, you can fix them. Once they are fixed, your app runs smoothly.

  • Ashutosh avadhani

    I’m getting this particular error::–

    1) 01-30 15:32:35.948 30375-31449/info.androidhive.loginandregistration E/Volley: [322118] BasicNetwork.performRequest: Unexpected response code 412 for http://192.168.43.2/android_login_api/register.php.

    2) 01-30 15:32:35.968 30375-30375/info.androidhive.loginandregistration E/RegisterActivity: Registration Error: null.

    What can be the error?

  • rakan

    please someone help

    i got this error:
    Error:Unsupported method: BaseConfig.getApplicationIdSuffix().
    The version of Gradle you connect to does not support that method.
    To resolve the problem you can change/upgrade the target version of Gradle you connect to.
    Alternatively, you can ignore this exception and read other information from the model.

    the program doesn’t call volley in so both
    RegisterActivity and LoginActivity
    are having errors

  • Open http://My laptop(IPV4 ip)/android_login_api/login.php from your mobile chrome browser. It should echo some response otherwise the mobile is not able to access your laptop via your WIFI.

  • Jamal Jalloh

    Hi,

    I’ve been stuck with the error {“error”:true,”error_msg”:”Required parameters email or password is missing!”} for some time now. To give some context I have not yet started the android bit of this project as am focused on getting the login php section working first. I have made very minimal modifications to the code which I have listed below:
    – Removed password encryption (just for now, will look to implement later), therefore removed salt and encrypted password variables. to check password i simply compare. This may be better explained through the images I’ve attached.
    – Purely focused on the login part of this project
    Please see the attached pictures of my scripts and the postman output, these will with out a doubt better explain what I’m trying to say. Any help would be appreciated greatly 🙂 https://uploads.disquscdn.com/images/b604cfb5ea74d9c49bff44e0fae055a292199c4c601e93e75b70e3cfa6ad474e.png https://uploads.disquscdn.com/images/6b6d767a89411fbaa8f94005e5e7ba1a0de51e860657b553f1aeb01f7ea9cc23.png https://uploads.disquscdn.com/images/7e2745e7f7238f0f28f9d971661fec6d77fb8a8cb3a2f83b9f21943f1e86e224.png https://uploads.disquscdn.com/images/8292c801ff4f466c387a5595dea958b50f0a07cf69e40dab0f31a955f7d555e6.png

  • Okiring

    Hello…i did everything as per the code you posted but am getting a jsonexception error saying string cant be converted to jsonobject..need help..

    • Check the same endpoint using Postman where you can see the php errors and fix them.

  • luthfi widya ekakusuma
  • RAHUL SAH
  • Christian Munch Hammervig
    • abhishek saini

      i am having same error…plzzz solve

  • Christian Munch Hammervig

    Register works but login gives me this:

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

    I tried to gist my LoginActivity but then my comment was removed

    • Seems you are not getting JSON response. Check the URL in Postman before trying them in Android. In Postman, you can see the PHP errors and fix them.

      • Christian Munch Hammervig

        I can’t get postman to work i keep getting an error saying {“error”:true,”error_msg”:”Required parameters email or password is missing!”}

  • Yohan Hemal
  • Justinas Vijeikis

    Hi, I would like to ask you how to read a column from sql file to app. Like example in user table I create new column points and i want get values in app.

  • Rahul Saxena SAXENA

    Hi Ravi,
    can you plz resolve this >>>>>java.lang.string cant converted to jsonObject,
    i am getting this popup after run the application

    i am using online server db link instead of localhost

    • Check your online server URL with Postman first. You might see PHP errors, fix them first.

      • Rahul Saxena SAXENA

        hi ravi,
        i cross check but in postman i am getting the correct response like:

        {“message”:”success”,”status”:true,”data”:{“id”:”468″,”email”:”sidvidrokz@gmail.com”,”password”:”3719b0d81c17fa1a293803796de549dc205d0dce”,”salutation”:”1″,”first_name”:”Siddhant”,”last_name”:”Agarwal”,”birth_date”:null,”registration_no”:”00000468″,”gender”:”1″,”mobile”:”9811626460″,”qualification”:null,”mci_number”:null,”consultation_time”:”20″,”patient_key”:null,”avatar”:null,”facebook”:null,”google_plus”:null,”twitter”:null,”user_type”:”4″,”ip_address”:”47.30.170.210″,”identity_type”:null,”identity_id”:null,”is_active”:”1″,”is_verified”:”1″,”is_deleted”:”0″,”prev_rating”:”0.00″,”avg_rating”:”0.00″,”added_by_doctor_id”:null,”added_by_laboratory_id”:null,”otp”:null,”created”:”2018-01-18 12:26:49″,”modified”:”2018-01-18 12:26:49″,”marital_status”:null,”blood_group”:null,”occupation_id”:null,”address”:null,”state”:null,”city”:null,”ethnicity_id”:null,”identity”:null,”full_name”:”Siddhant Agarwal”}}

        but when i run the app in my andriod phone , i am getting this popup msg
        json error:Value >
        package activity;

        /**
        * Created by RahulReign on 30-01-2018.
        */

        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 app.AppConfig;
        import app.AppController;
        import helper.SQLiteHandler;
        import helper.SessionManager;
        import instatag.com.phpintegrationtry2.R;

        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 username = inputEmail.getText().toString().trim();
        String password = inputPassword.getText().toString().trim();

        // Check for empty data in the form
        if (!username.isEmpty() && !password.isEmpty()) {
        // login user
        checkLogin(username, 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 username, 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 message = jObj.getBoolean(“message”);

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

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

        JSONObject data = jObj.getJSONObject(“{data}”);
        String first_name = data.getString(“first_name”);
        String email = data.getString(“email”);
        String created = data
        .getString(“created”);

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

        // 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(“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 message) {
        Log.e(TAG, “Login Error: ” + message.getMessage());
        Toast.makeText(getApplicationContext(),
        message.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(“username”, username);
        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();
        }
        }

        https://uploads.disquscdn.com/images/cbeb149cc70b5c14bf40488cb5ee2d95713e73e89b566e9a21e109ad5767e5b6.jpg

  • Could you provide me temporary username / password to test your api?

    • Rahul Saxena SAXENA

      ya sure check with this>>
      username :sidvidrokz@gmail.com
      password :123456789

  • Siddhant Agarwal

    https://uploads.disquscdn.com/images/641b52964a74b7f6caa92a4624ce3263b3b751140b878e372a9f2f93138d9235.jpg

    Hi ravi

    I am getting correct json response when i am running my application on emulator
    but error html response when running on the actual device(see image)

    You can check the code below:
    public class MainActivity extends AppCompatActivity {
    //public static final MediaType MEDIA_TYPE = MediaType.parse(“application/json”);
    Response response;
    TextView res;
    //String s=””;
    Handler mHandler;
    EditText email,password;
    Button login;
    // OkHttpClient client;
    String username= “manjeet.patel@ignitershub.com”;

    public static final MediaType JSON
    = MediaType.parse(“application/json; charset=utf-8”);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    email=(EditText)findViewById(R.id.email);
    password=(EditText)findViewById(R.id.password);
    login=(Button)findViewById(R.id.login);
    res=(TextView)findViewById(R.id.response);
    // client = new OkHttpClient();
    //Log.i(“MainActivity”, “onCreate: “+email.getText().toString());
    //Log.i(“MainActivity”, “onCreate: “+password.getText().toString());

    login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    OkHttpClient client = new OkHttpClient();
    JSONObject postdata = new JSONObject();
    try {
    postdata.put(“username”,email.getText().toString());
    postdata.put(“password”,password.getText().toString());
    } catch(JSONException e){
    e.printStackTrace();
    }
    HttpUrl.Builder urlBuilder = HttpUrl.parse(“http://feish.online/apis/login”).newBuilder();
    String url = urlBuilder.build().toString();
    RequestBody body = RequestBody.create(JSON, postdata.toString());
    final Request request = new Request.Builder()
    .addHeader(“X-Api-Key “,”AB5433GMDF657VBB”)
    .addHeader(“Content-Type”, “application/x-www-form-urlencoded”)
    .url(url)
    .post(body)
    .build();
    client.newCall(request).enqueue(new Callback() {
    Handler mainHandler = new Handler(MainActivity.this.getMainLooper());
    @Override
    public void onFailure(Request request, IOException e) {
    Log.i(“Activity”, “onFailure: Fail”);
    }
    @Override
    public void onResponse(Response response) throws IOException {
    final String body = response.body().string();
    // Log.i(“AT”, “onResponse: “+response.body().string());
    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    updateUI(body);
    }
    });

    }
    });

    }
    });
    }
    private void updateUI(String responseBody){
    // Toast.makeText(this,responseBody,
    // Toast.LENGTH_LONG).show();
    res.setText(responseBody);

    }
    }

  • a girl has no name

    Attempt to invoke virtual method ‘void com.danalex.qrcode.rabiesvaccination.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)’ on a null object reference

    I followed everything bit I’m getting this error

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

  • Victor Cabeza Cifuentes

    Hi Ravi, i have one problem, when i try to register or login the app stops and close, but when i use postman to store an user it works perfect, do you know why?

  • GPU IT

    https://uploads.disquscdn.com/images/216bb8b935f01ed771af0b83d9a923cae34a319958aef6e1840ec9c461c67c4c.png How about this problem? Have try using postman but getting a “Login credentials are wrong”

  • Wan Yik Mun
  • Adedokun Adekola

    i really love your tutorial it help me,
    pls can you tech me how to update user infomation from database with this rest api above
    God will bless you

  • Kill3bill

    Hi Ravi, thank you for the huge tutorial, it’s been a great help!
    However I’m getting the following error even though that all values are stored in the database.
    Adding postman screenshot as well.
    What should I do?
    Thanks!
    https://uploads.disquscdn.com/images/3f6e55843454c1b2d5a975d2d182d5397c93df076cc57da22b213de61b9b7e93.png https://uploads.disquscdn.com/images/3c273f52e25dde319cdc18393ed57635cc1ef23c0c0852e21ba96b95b72fa89d.png

    • You can see register.php, DB_connect.php garbage printed along with JSON. Go through all files and comment those line. I think those lines left somewhere in the PHP and they are getting printed along with JSON.

      • Kill3bill

        Ohh! damn. I thought It was a part of it..
        silly me..
        Thank you!

  • Mario Cardona

    Hi , im having some issues running your example , i get this error :
    Register Response: Fatal error: Call to undefined method mysqli_stmt::get_result() in line 45 on DB_Functions.php https://uploads.disquscdn.com/images/c1a67a67bdfd0d5944de8500cd93b5f55fb9baa432221e9e560a1ec0f7d2367c.jpg

    • You need to enable mysqli extension.

      • Mario Cardona

        It is already enabled. I manage to register a user, but the app breaks after the insert in the database. I am using an older version of php. Do you think that´s the problem?

  • gorang agrawal

    Hello Sir,
    I am getting a 500 Server Error while Register and Login process

    • Check the php / apache error logs

      • gorang agrawal

        Got the error Sir,

        It was due to compiling wrong Volley library

        Tnx for the help

        BTW Can I use all of this for my own App? Which will be on PlayStore

  • Shobhit Gupta

    hello there,

    if there is no internet then how data will store using sqlite in mobile phone only, and once we connected to internet then how data are synchronized with the mysql,

    please help, i go though your code but didn’t find method to save data in above scenario.

  • Md. Azizul Alam (Toton)

    I am getting 500 Server Error. I have hosted it on A2Hosting Server. When I am trying to login through Postman it also returning 500 Server Error. In another question someone got the same problem, but his problem solved by changing the Volley library. I am not understanding what is the relation between Volley library and this error. I am using Google Volley Library rather than Maxioke. When using in App. the Toast returning Blank both for login and register but wondering that the registering row is inserting in the table.

    • Check your server error logs and fix the errors.

      • Md. Azizul Alam (Toton)

        There is no error log in server. 🙁

      • Md. Azizul Alam (Toton)

        Sorry, I am using A2Hosting Shared turbo hosting. I dont know its Apache or Nginx. According to their instruction I didn’t found anything in cPanel Error Log.

      • Md. Azizul Alam (Toton)

        I told A2Hosting about the issue now there is no 500 internal error. But its returning “Uncaught Error: Call to undefined method mysqli_stmt::get_result()” error on DB_Functions line 64

      • Md. Azizul Alam (Toton)

        By Google search I found I need mysqlnd driver. But my server is shared and they will not support for mysqlnd driver. WHat should I do?

        • Then you need to change the PHP mysql related code.

  • Arnab

    My app is crashing with NullPointerException. Screenshot Attached. Help Needed. https://uploads.disquscdn.com/images/4493fce3e7c8291077f54fe3a41ae4bf5090e438b8c575b3dca15661aebbd13d.png

  • Asad Ullah II

    when i click on login app going to Closed

  • Mishrat Khan

    your login not working?

  • Arumann

    sir,code is not working.

  • Irum Jadoon

    I am receiving this error can u let me know how to solve it?
    http://localhost/android_login_api/register.php: {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

    • Syed Zulqarnain

      i am getting the same error. the top comment here is also about this error and has some discussion but nothing to resolve this error.

      • Are you getting the error while trying from Postman?

        • Irum Jadoon

          solved

        • Syed Zulqarnain

          no. using postman i can easily embed these details in body but i don’t know how to do that in http request from android app

          • Pls post your code.

          • Syed Zulqarnain

            This code is actually from your tutorial.

            private void registerUser(final String name, final String email,
            final String password) {
            // Tag used to cancel the request
            String tag_string_req = “req_register”;

            pDialog.setMessage(“Registering …”);
            showDialog();

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

            @Override
            public void onResponse(String response) {
            Log.d(TAG, “Register Response: ” + response);
            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”);
            if (!errorMsg.isEmpty()){
            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:”+error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
            }
            }) {

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

      • Irum Jadoon

        there was a problem in manifest file .

        • Abelardo León González

          Which one, @irumjadoon:disqus ?

    • Abelardo León González

      Me too.

      Let me know if you could solve it, please.

      Any help would be welcome.

      Best regards.

  • Hasara Maithree

    Thank you very much. How do I run this in actual android phone? (not in emulator) What dependencies do I need to add? How to access api from phone?

  • Griffin

    Hello @ravi8x:disqus …. thank you for such a wonderful tutorial, You make life easy for some of Us who are beginners.

    This is just a quick point out to many guys facing this same error in the Login activity where the response being received in not in json format. Just like in the photo below.

    I came across it today but my case looks different: After importing the database schema you provided into xampp(mysql), the table structure changes(name becomes NAME). I only figured that a moment ago and this is really strange.

    Guys should check to see if the table naming structure matches exactly the schema you provided in the tutorials. This is the command i used to fix

    ALTER TABLE `users` CHANGE `NAME` `name` VARCHAR(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL;

    • Thanks Griffin for your suggestion. I’ll update this article with latest versions of PHP and MySQL.

  • Krishnaraj Naik

    Hi… I have tried developing an login and registration app similar to the above code, But when i run and click on the login button from login screen a toast message pop up saying :
    Login Error: javax.net.ssl.SSLHandshakeException: Handshake failed
    Can anyone help me to resolve this problem

  • iliyas

    this code worked for me but When i am logouting the user,All the details was deleted.Again i have to registering the details and login into the application.Tell me please how to logout without deleting Stored values.

  • Abelardo León González

    NICE TUTORIAL, @ravi8x:disqus YOU ARE THE BEST!

  • Abelardo León González

    Another important thing here is the port when you are using MAMP. You should ensure to use the port 80 and not the ports supplied by MAMP (8888) in order to run the Android app.

  • Abelardo León González

    Hi guys:

    Following are the screenshots which belong to the different settings in order to run this sample made by @Ravi Tamada:

    MAMP (OS X):
    1) https://uploads.disquscdn.com/images/bed849dce1b112599a2ebc154bc270c530ba7dad62f5bb37b87ccf961e0a51b0.png
    2) https://uploads.disquscdn.com/images/5895a5c635d00660c6d985de1eee6075151e973526789b933c76873220d82513.png

    POSTMAN:
    1)
    https://uploads.disquscdn.com/images/0b17ad65d64aff3757f70cd70aa1f3ab49a38bec40a0553cf3a09b6e8c62c612.png

    ANDROID (AppConfig):
    1)
    https://uploads.disquscdn.com/images/9b4208c73d48a7ca6557f09b93d92282b234233c403a9f88cb778311bb3ea59e.png

    PHPSTORM (PHP):
    1) Please, take in account that the password here showed was randomly generated by phpadmin (see below how to do this):
    https://uploads.disquscdn.com/images/1f196ddec4451bc6cc71e36c40707469179320303307b3b6cd8f219d1b82c793.png

    PHPADMIN:
    1) Generated password here has to be written inside the Config.php (see above): https://uploads.disquscdn.com/images/6005be627c2cbf417aa5c79ee86d9e834420682a677d2074a912b2d8c54cf8cd.png

    IMPORTANT: Since the parameters are retrieved by using the POST method, you CAN’T use a browser of this way: https://uploads.disquscdn.com/images/0d0cb256b1d49df3a6db97385d53a969bed711c7b2f632a64fc394188b8b1451.png

    Please, let me know if you have any issue. 🙂

    Best regards.

    • Very good observations and thanks for your valuable information Abelardo 🙂

      • Abelardo León González

        Without your work, we wouldn’t be nothing on Android 🙂

  • Mert

    but after succesfull login how to make requests from that user. i mean how server side know this request is coming from which user

  • indra

    hello!
    can you guys help me figure out on how to set the php – database properly, I got an error when accessing http://localhost/android_login_api/register.php it says Warning: mysqli::mysqli(): (HY000/1045): Access denied for user ‘raporkudev’@’localhost’ (using password: NO)
    I did the same Config.php as instructed except the DB_USER changed value. tbh, I’m new to this so pardon me if my explanation confuse you

    • Have you defined your mysql password correctly in Config.php?

      • indra

        I try everything. I leave it blank, fill it with numeric only. still got the same error, the difference only in error line (using password: YES).
        ow for the addition, I googling regarding this matter before, they say it has thing to do with user/host using wildcard value of % but I don’t really understand what’s that mean

        • try login in Terminal or PhpMyAdmin and see if the correct password is used. Or reset your mysql password

          • indra

            done it. tried to change password when logging in mysql with new user/pass (reffereing to Config.php) but it says #1045 – Access denied for user ‘raporkudev’@’localhost’ (using password: YES)
            it logged me in if I simply type root as a username and type the password that I provided (changed password)
            here my Config.php

            what I missed?

          • Krishnaraj Naik

            Just try temporarily replacing POST method with GET method in register.php and login.php,
            and in URL type => localhost/database_name/register.php?name=abc&email=abc@g.com&password=abc

            This will give you the result. But replace GET method with POST method once you are finished checking the working of php code since POST method is secure than GET method while sending data to server.

          • Thanks Krishna 🙂

          • Krishnaraj Naik

            Ravi can you help me with ssl certificates since from past few days I am trying to overcome the error but not able to clear the error.
            May I know type of certificates should I install

          • Is it your own server?

          • Krishnaraj Naik

            No. I work on local host

          • Okay. If it’s localhost try using http instead of https. Also use Retrofit and add TLS Ciphers to avoid this problem.

          • Krishnaraj Naik

            Thnx Ravi.

  • Tuga Dyrdek

    Hello, is there any toturial on a forget password system that implements PHPMailed and MYSQL in androidhive?

    Thanks for the attention.

  • Muhammad Waqas Irfan

    Hello Ravi this tutriols work perfectly with xampp server
    But i was transfer all php files into cpanel and make database its does not working please tell me what is the base_url of this cpanel please tell me

    • Muhammad Waqas Irfan

      please sir tell me

    • That depends on your hosting server. The base url should be some where on the dashboard and you can include the path of your php project.

      • Muhammad Waqas Irfan

        sir base_url is http://www.dev4sol.com and i was make a folder of android_login_api where php files are upload but when i was try to register in android a block spot come and nothing please tell me how to resolve it

        • The php should be kept inside the same folder of https://www.dev4sol.com/ home page. Should not be placed next to it. Keep the android_login_api inside the same project and access https://www.dev4sol.com/android_login_api/register.php via POST method using Postman.

          What is the path of your main website on the server? It should be something like /var/www/html/xxx

          • Muhammad Waqas Irfan

            Sir tell me how to resolve this

          • Muhammad Waqas Irfan

            tell me

          • Abelardo León González

            Muhammad, Ravi asked you for a piece of information.

            He is waiting for your response. 🙂

          • Yup

          • Muhammad Waqas Irfan

            yup this is in my cpanel and i was make an folder in this as well but same result

  • Ahmed Chouihi

    Thanks Sir , It works with Wamp . I don’t know why it did not work for me with Xamp

    • Okay. May be problem with configurations.

  • It seems your home path is configured as /public_html/MAIN_WEBSITE_PROJECT in apache / nginx config. What is the project name of your main website that is currently running. Keep the android_login_api inside that project.

  • Muhammad Waqas Irfan

    sir please tell me i am so sad about this i had tried this work 9 to 10 times with different way but same result is happen a black spot come and nothing happen

    • If all the files are placed properly, it should work. When I accessed your path, I am getting 404 error. Can post your Filezilla screenshot?

  • Then it’s working fine. You need to access the url with proper method GET / POST and with correct parameters. Use Postman to send the request.

    • Muhammad Waqas Irfan

      sir please help me in postman i was never use this

      • Muhammad Waqas Irfan

        how to use with postman i have an index.php instead of register and login php files

    • Muhammad Waqas Irfan

      sir please tell me how to work on postman with parameters

  • Access the url first from Postman and verify everything is working fine. Then try them in android app. Use the router IP address instead of localhost.

    • hasim shaikh

      in postman if i register with same credentials, it is showing me
      ERROR: TRUE User already Exist

      but when when i insert different name, email and password it inserting in database when i see in backend it is there, but in postman No JSON reply, nothing.. total black output..

      same happening when i am doing login with correct credentials…

      Here i am asking when it is replying for already existed user by checking in database and inserting data properly without any error.

      then why it is not showing ERROR: FALSE message in JSON when i successfully login or i successfully registered ?? why total blank reply??

      • There might be php errors. Check the php error logs and enable error reporting in PHP code.

  • Naveen Kumar Reddy Pemmana

    Hello sir,
    please help me, i had created an app only for login which uses unique_id and password which is stored in mySQL database but there is problem in json response.
    json response output:
    Config.php {
    “error”: false,
    “Status”: “Success”
    }
    i am unable to understand why Config.php is being printed in json response. please take time to check this code sir. Thanks in advance

    #Login.php
    FALSE);

    if (isset($_POST[‘unique_id’]) && isset($_POST[‘password’])) {

    // receiving the post params
    $unique_id = $_POST[‘unique_id’];
    $password = $_POST[‘password’];

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

    if ($user != false) {
    // user is found
    $response[“error”] = FALSE;
    $response[“Status”] = “Success”;
    echo json_encode($response);
    } else {
    // user is not found with the credentials
    $response[“error”] = TRUE;
    $response[“Status”] = “Login credentials are wrong. Please try again!”;
    echo json_encode($response);
    }
    } else {
    // required post params is missing
    $response[“error”] = TRUE;
    $response[“Status”] = “Required parameters unique_id or password is missing!”;
    echo json_encode($response);
    }
    ?>

    #DB_Functions.php
    conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

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

    $stmt = $this->conn->prepare(“SELECT * FROM users WHERE unique_id = ?”);

    $stmt->bind_param(“s”, $unique_id);

    if ($stmt->execute()) {
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $db_password = $user[‘password’];
    if ($db_password == $password) {
    // user authentication details are correct
    return TRUE;
    }
    } else {
    return NULL;
    }
    }

    }

    ?>

    • Check all the files and remove Config.php in the comments. It might be printing from the comments.

      • Naveen Kumar Reddy Pemmana

        It worked! Thanks a lot sir!

  • Tee Sammy

    Hi I keep getting Volley error : null on my app, what do I do please

  • Yassine Amouur

    hi i have problem in code

  • Johan Riascos Segura

    thanks for sharing your knowledge, I have a specific problem, I can register but not log in, the sale is an error as a JSON error: the value <br of type java.lang.String can not be converted to JSONObject, how can I solve this problem . Thank you!

  • Johan Riascos Segura

    thanks for sharing your knowledge, I have a specific problem, I can register but not log in, the sale is an error as a JSON error: the value <br of type java.lang.String can not be converted to JSONObject, how can I solve this problem . Thank you men!

    • There might be PHP errors. Make the login request from Postman and see the errors.

  • brian

    Hello, Ravi. thanks for the good tutorial . The code works well on localhost.
    However when i transfer it online, i get the following error [7295] BasicNetwork.performRequest: Unexpected response code 500 for URL
    When i test my url using postman i get this {“error”:true,”error_msg”:”Required parameters email or password is missing!”}
    What could be the problem.
    Thanks in advance

    • The 500 error reports can be seen on the server error logs. Find the error log depending on the server you are using apache / nginx.

      • brian

        Im using apache..But i cant locate the error

  • Sagar Arora

    I have two errors
    1 is Fatal error: Class ‘DB_Connect’ not found in C:wampwwwandroid_login_apiincludeDB_Functions.php on line 11

    https://uploads.disquscdn.com/images/448efb5050527636c8520dfebe5abef2c966483e62b98899b76a583947c2d9d2.png https://uploads.disquscdn.com/images/7402f4f8487bc96925b72ece786869bf1db5075c49eb19a326e59b487978d1d9.png

    And 2nd is my app crashes before going to the login page
    Says that — java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zelectrospace.ramikki/com.zelectrospace.ramikki.account}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.widget.AppCompatTextView.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference

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

    https://uploads.disquscdn.com/images/68903e0a5bd7d67908023ff90ffd9e71b0e43d888a388e1659db1aae5fb8abc2.png

    Please Tell me the solution as early as possible.
    Thanks..

    • You need to include the DB_Connect file using include or require_once. I added that line already. Please verify once.
      https://www.daniweb.com/programming/web-development/threads/156857/fatal-error-class-not-found-help

      • Sagar Arora

        and the second error please

      • Sagar Arora

        I have already connected that DB_connect.php file

      • Sagar Arora

        please tell me about the 2nd error

        • It’s throwing null pointer exception on TextView. Did you use findById on TextView correctly?

    • Abelardo León González

      1st problem) It looks like it is a path issue:
      Are both files stored in the same dir? Please, could you post a screenshot of your directories including files?

  • Amit Sharma

    i have this error “Couldn’t read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.” i changed code of sqlitehandler class and add a column in this.
    help me please!

  • haru hardadi

    in activity login erorr with coment Json error: Value <br of type java.lang.String cannont be converted to JSONObject

  • haru hardadi

    coment in activity login

    Json error: value <br of type java.lang.String Cannont be Converted to JSONobject

    • Abelardo León González

      Hi @haruhardadi:disqus ,
      Could you explain it more detailed, please? Thanks. Brs.

  • iliyas khan

    Thank you for Wonderful tutorial…its working Perfect for me..Thank you Bro.

  • Haleema Sadia

    sir can we use this method to connect android to webserver using codeigniter framework?

    • Yes we can. All you have to do is build Restful services using Codeigniter and consume them from android.

      • Haleema Sadia

        sir can you please give me any guide tutorial to connect codeigniter with android.. actually i am trying to do it i am using the controller file to fetch variables.. but i dont know how to access methods in codeigniter controller file.. I dont have any idea but still i am trying please give me any guide sir. Thankyou in advance

  • Kenneth Mitre

    Sir what is the error of this.
    E/RegisterActivity: Login Error: null
    04-21 20:48:34.993 23923-26633/? E/SensorManager: RegisterListener ACCELEROMETER type:1 delay:20000us by aswq
    04-21 20:48:35.462 23923-26633/? E/SensorManager: unRegisterListener by aswq.

    i can’t register and the data didn’t insert in the mysql database. please help me. thank you!

    • I think the php/mysql endpoint url is not accessible from your android app. Check the URL again.

  • I think table name shouldn’t start with number. Try keeping your table name to usuarios50

    https://stackoverflow.com/questions/3694276/what-are-valid-table-names-in-sqlite/41288018

  • Tarik M’ghari

    Sir can you please help me ?

    • It seems you forgot to add AppController to manifest file.

      • Tarik M’ghari

        thank you sir

  • Tejpal Bhangale

    @ravi8x:disqus Hello Sir.. all Tutorial is working fine.. but i want forget password button with this. Im not getting how to decrypt that encrypted password with salt stored in database table. Please help to decrypt password…

    • Hi Tejpal

      The password can’t be decrypted. For forgot password why we need to decrypt password again as user has to enter new password.

  • Irfan Khan

    Really Helpfull Article 🙂 Thanks

  • Abdulhakim Mohamud Ismail

    when i register user and when i login it said this error sir Json Eror : value<br of type .java lang.string cannot be converted to JsonObjects

  • Abdulhakim Mohamud Ismail

    hello sir when i click the login activity and i enter my email and my password it will toast this error can you help me plz
    Json Error :Value<br of type java.lang.String cannot be converted to JsonObject

    • First test your PHP code with Postman client making the same requests. You can see the PHP errors there and fix them.

      • Abdulhakim Mohamud Ismail

        how can i fix that error in the php can you give me hints sir

        • First you need to enable error reporting in your php code. Make call from Postman to your php endpoints. If there are PHP errors, they will be printed along with JSON. You can google around and fix them. If you are getting 500 error, check apache / nginx error logs .

  • Jhazzier Pineda

    Hey there, sir Tamada. I was wondering if you could help me with a problem I’m having here.

    You see, I’m working on localhost with wamp, but when I try to access the server from another device connected to the same wifi network, it says I don’t have permission to do so, and thus, when using the app, it crashes when register or login buttons are tapped, since they request info from the server.

    How do I grant acessing permission to the server?

  • Emmanuel
    • Emmanuel

      Hello Ravi,
      I still have this error. Could you help me dealing with that?

      • Hit the Login URL from Postman and see the response. You can find PHP errors if there are any. Also enable error reporting in PHP code first.

        • Emmanuel

          Hello Ravi,
          I dont have any php errors from Postman, but i still have the error message “Login credentials are wrong. Pleas try again”. Do you want me to send to you my java code? I cannot find what is wrong. Because i can register but i can’t log in even if the credentials are correct. And the user data “userId, userName, userPass” are stored correctly in DB.

  • There might be PHP errors. Hit the same URL using Postman to see the PHP errors.

  • Adnan

    Hello Ravi,
    I have one question, I did everything like you and it doesn’t show any error. But when i launch my app, it shows me login screen, when i press register and open register screen when I fill all input fields and press button it doesn’t back me to login, and not store to my database, just show me a little grey circle. I downloaded your whole project and tried with your source code the same thing again. Tried with XAMPP (put folder in htdocs), tried with WAMPP (put folder in www) always the same. No error when i launch but when i press nothing happened in database. I tried with localhost and my IP (192.168.0.12). Also when I start services (Apache+MySQL) and hit URL/folder/register.php It shows me {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}.
    Best regards

  • Amin Taheri

    Thanks for beutiful article.
    I want to use imei as id for my users. I get the imei of my user’s device and add them as id in database. but i dont know how use send the imei of device to api for cheking with database?!

  • saket kumar

    Why I am getting this error ==== Registration Error: null

  • Вадим Макаров

    Hi Ravi! My english is very bad sorry for that. And so I rendered the PHP files to an external server and when I send a request to it them returns null in logcat show that: (… BasicNetwork.performRequest: Unexpected response code 403 …)
    What could be the problem?

    • You need to change the server configuration to avoid 403 error. Check the docs depending on the server you are using Apache or Nginx.

    • Вадим Макаров

      It’s problem on server. Just forgot.

      403 Forbidden

      403 Forbidden

      nginx-reuseport/1.13.4

      • Search for `Nginx 403 error`.

        • Вадим Макаров

          Thanks a lot Ravi for code and response. And now I’m trying to run scripts from the local Wampserver. Run URLwith Postman and I get an error from register.php {“datfi”:true,”error”:true,”error_msg”:”Required parameters (name, email or password) is missing!}. And i think may be it poblem of the server. Can you tell what do you think about this?

          • Вадим Макаров

            Sorry, i mean the greate code! Anyway, thanks a lot!

          • You are welcome 🙂

  • Otgoo Otgo
    • The register.php endpoint should be accessed via POST method. When opened in browser, it makes GET request. Use postman client to test the URL.

  • Arnav Kaushal

    Hi ravi , I am getting the following error:

    W/System.err: org.json.JSONException: Value {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

    and providing the params in the manner:
    http://localhost/android_login_api/register.php?name=arnav&email=arnav.kaushal800@gmail.com&password=password
    I get the same error:

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

    Both steps were done in postman.

    Moreover when I press register buttton, the progress dialog does not hide and the error is:
    –> W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

    I even logged the params output to see if the args were actually being passed which they are being:
    E/RegisterActivity: {email=arnav.kaushal800@gmail.com, name=Arnav, password=password}

    Please help as I have tried everything.

  • Ashwin Kumar

    This idea works when the wamp server and my mobile is in the same network.
    But it does not work when I connect my mobile to a different network.
    Can you please give me some idea on how to do this.

    • It supposed the work in same network as the server are running on localhost. If you want them to be accessed publicly, you need to host them on a server.

  • swanand joshi

    Hiii Ravi
    My APIS are working fine but I could not able to login through ui
    My Error:
    5-24 10:24:09.852 3874-3874/? E/RegisterActivity: Login Error: null

    I could not able to login

    • Seems the urls are not accessible from your Android app.

    • Abelardo León González

      Hi @swanandjoshi:disqus ,
      Not enough information about your issue.
      Please, either share code or share more detailed information: (logs).

      Regards.

  • swanand joshi

    Sharing you Screen Shots
    I am getting response as :
    https://uploads.disquscdn.com/images/5efddf3146a02b7eb6dd64a810551a7499034b68794e272509d832d1c9c845f2.png https://uploads.disquscdn.com/images/85db9001113f0ba91633c651b53335360f5650315289159b12f8269ee193f95d.png

    And I set role id for admin as 1 and user as 2

    My Api Keys :

    public static String URL_REGISTER=”http://192.168.1.103/BB/register.php”;
    public static String URL_LOGIN=”http://192.168.1.103/BB/login.php”;

    Testing on localhost from xampp server
    Kindly reply soon if any requirement in coding I will share you the project

    • If you are changing the SQLite table structure, uninstall and install the app again to see the newly added columns created.

  • Mirulesa

    https://uploads.disquscdn.com/images/ac02816e466c4de572c4a86ac9a2b9c52c2bde13c122198d19d1d87484c278e5.jpg

    im newbie at android, and when i found error like this i dont know how to solve it
    sorry at my english

    • adil

      android:name=”.AppController”

      • adil

        in manifest file below

    • Add AppController to AndroidManifest.xml

  • adil

    i have problem with Jason object in postman work fine and in app it shows java.lang.String cannot be converted to JSONObject

    • There might be php errors in the JSON or mobile not able to connect to internet.

  • Muhammad Faisal

    Hello ravi, fabulous tutorial there.

    I want to store int typed data into mysql using php. but it couldn’t.
    I try to store this custom library value into database (i.e 1 to 5) https://github.com/sujithkanna/SmileyRating

    Is this method works?

    • Whats the problem in storing int? Any errors you are getting?

      • Muhammad Faisal

        Yes i got errors, because the data is int typed.
        The problem comes from the registerUser() which is mostly has a lot of String typed data.
        The android studio told int can’t be converted into String, so i thought i have to learn and make API myself for this int data typed. But it’s funny, because i add phone in the fill form, and it’s fine!
        But i already solved the problem, by converting this int data typed into Integer first, then using toString().

        Anyway thanks for your tutorial and kind reply ravi!

        • Cheers!

          • Muhammad Faisal

            Hello again ravi!

            I’ve got some ridiculous question lol. :v
            I don’t know why its happened, but im almost stressed because of it..

            previously, using your tutorial to solved my database insertion was fine, moreover it solved some problem that i thought it couldn’t be used to.

            All goes well, but after some time, suddenly the data can’t be inserted into database. I’ve check the matchness of my IP address in the AppConfig, i’ve check the code in the android and the code in the PHP.

            Before the bug, there was no problem. i didn’t changed the code, the connection is ok, and the data was inserted into database, but it just happen suddenly!

            Would you mind to take a look at the logcat? Is there any hints that can lead me into the problem?
            here it is:
            07-18 18:05:44.532 5339-5339/? E/libprocessgroup: failed to make and chown /acct/uid_10044: Read-only file system
            07-18 18:05:44.532 5339-5339/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
            07-18 18:05:44.532 5339-5339/? I/art: Late-enabling -Xcheck:jni
            07-18 18:05:44.564 5339-5347/? I/art: Debugger is no longer active
            07-18 18:05:44.730 5339-5339/? I/InstantRun: starting instant run server: is main process
            07-18 18:05:44.769 5339-5358/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
            07-18 18:05:44.772 5339-5339/? D/Atlas: Validating map…
            07-18 18:05:44.809 5339-5358/? I/OpenGLRenderer: Initialized EGL, version 1.4
            07-18 18:05:44.809 5339-5358/? D/EGL_adreno: eglCreateContext: 0xad824c40: maj 2 min 0 rcv 2
            07-18 18:05:44.812 5339-5358/? D/OpenGLRenderer: Enabling debug mode 0
            07-18 18:05:49.860 5339-5339/com.example.android.feedbackcustomernew W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
            07-18 18:06:39.072 5339-5339/com.example.android.feedbackcustomernew D/Form: Register Response: {“error”:false,”uid”:”5b4eef2e226f33.11524145″,”user”:{“name”:”debug”,”email”:”debug@gmail.com”,”phone”:”083123456789″,”critic”:”debuging unknown bug”,”created_at”:”2018-07-18 14:41:34″,”updated_at”:null}}

            thanks for any helps.

          • Usually the IP address will change whenever device connect / disconnect from WIFI. Check the IP address every time and change in android code.

          • Muhammad Faisal

            I solved the problem!
            After some time wondering what and where the bug come from, i was sure that the bug wasn’t come from the code, or the IP matchness.

            But finally, i realized that i was using IP Public/Global from a provider which the configuration had been changed by network technician that myself dont understand about.

            So i try to use Local IP using RJ 45 cable and all data insertion goes well.

            Thank you for your kind reply!

          • Great!

          • Muhammad Faisal

            Hi Ravi, by the way, right now im getting further with some PHP and MySQL PDO or MySQL object oriented (i don’t know what its called?) code customization to fulfill my needs.
            But i don’t understand well about (i.e $stmt->, bind_param() and etc..), since i used to use only a standard MySQL query structure.

            I want to learn more and further but having a bit difficulties to find a good reference so, what i wanna ask is, Do you have a tutorial which is explain about this completely, or another references, please?

          • Hi Muhammad

            As you already spent lot of time on PHP, I suggest trying PHP frameworks like Laravel… to make things easier.

          • Muhammad Faisal

            Is the PHP code that you used in that tutorial using Laravel Frameworks?
            If yes, then I’ll go further and deeper to learn Laravel.

            Also, this can help me to decide, which one is im gonna learn.
            Because I learned some like this not using Volley, but using RetroFit.
            It’s kind of harder than the tutorial you wrote, I thought…

  • SenseiKelvs Ricafort
    • The login / registration url is not accessible in your android device. Open the same url in device Chrome and see what happens.

      • SenseiKelvs Ricafort

        not running 🙁 thanks

  • Bhargavi S

    can any one reply me please ……

    • The login / registration urls are accessible from your mobile. Open the same url in mobile chrome browser to see the problem.

  • SenseiKelvs Ricafort
    • Is SessionManager class initialized before calling isLoggedIn() ?

      • SenseiKelvs Ricafort

        yes

  • Help

    HI
    Can I open this project in 1111111111?
    I’m trying, but there are always mistakes.

  • Steve Dench

    Hi,
    New to Java / Anroid studio.
    I have downloaded the code – I have android studio — is there a tutorial on how to load / import the code into android studio as all of my attempts have ended in errors.

    • Hi Steve

      If you are very new, I suggest learn the android basics instead of directly jumping to this article.

  • Mark Azteca

    Hi Ravi

    I am from Argentina but I live in Belgium

    It is just to say … THANK YOU VERY MUCH
    for the efforts that you put to help other programmers not so advanced like you. !!

    Regards

    • You are welcome Mark. Your feedback is much appreciated 🙂

  • VisionSol

    Hello SIr,
    How to decode that encrypted password? I want forgot password feature in this app..
    Please provide function for forgotPassword(emailid); I will send sms or email password to user(That i have done…)

  • Julius Mutunga

    Call to a member function bind_param() on null in /home/thirdway/public_html/.thirdway_takeapp/DB_Functions.php on line 83? Somebody please help

  • Drien

    Hello, nice tutorial !
    Can you help me ? When i try to change from activity, the app crashes
    Do you have an idea why ?
    Thanks in advance

  • Nguyễn Phú Khánh

    Hello Ravi,
    I’m trying to do a login function but it have something wrong with my example.
    When I call function checkLogin by click to button Login, it didn’t go into function onResponse of StringRequest. Instead of that, it go into onErrorResponse and show the message “Check error response”. Do you have an idea?
    Sorry for my bad English, thanks. https://uploads.disquscdn.com/images/6df2698d05d5d72c8a52986761c093925f0437cfda1430b9b264397aeed7cdf7.png

  • vidhya

    hi sir
    i got an error while login and registeration
    cleartext http traffic to my ip is not permitted. i use
    xampp

    • vidhya

      fix that error. but shows {“error”:true,”error_msg”:”Required parameters email or password is missing!”}’,

      • vidhya

        when i tested using postman, there was no error. can register and login.
        in my app i think
        StringRequest strReq = new StringRequest(Request.Method.POST,
        AppConfig.URL_LOGIN, new Response.Listener() {
        its not working. goes to json error.toast shows nothing.

        • vidhya

          logcat response

          • vidhya

            0/com.test.mediqnct.mediqnct I/Choreographer: Skipped 163 frames! The application may be doing too much work on its main thread.
            07-12 04:13:05.603 22270-22270/com.test.mediqnct.mediqnct E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
            07-12 04:13:05.606 22270-22270/com.test.mediqnct.mediqnct E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
            07-12 04:13:28.564 22270-22270/com.test.mediqnct.mediqnct W/art: Verification of org.apache.http.HttpEntity com.android.volley.toolbox.HurlStack.entityFromConnection(java.net.HttpURLConnection) took 239.840ms
            07-12 04:13:28.950 22270-22270/com.test.mediqnct.mediqnct W/art: Verification of void com.android.volley.toolbox.BasicNetwork.addCacheHeaders(java.util.Map, com.android.volley.Cache$Entry) took 295.420ms
            07-12 04:13:29.023 22270-22270/com.test.mediqnct.mediqnct I/Choreographer: Skipped 107 frames! The application may be doing too much work on its main thread.
            07-12 04:13:29.979 22270-22270/com.test.mediqnct.mediqnct I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
            07-12 04:13:32.788 22270-22270/com.test.mediqnct.mediqnct E/RegisterActivity: Login Error: null
            07-12 04:13:34.356 22270-22270/com.test.mediqnct.mediqnct I/Choreographer: Skipped 81 frames! The application may be doing too much work on its main thread.
            07-12 04:14:38.127 22270-22270/com.test.mediqnct.mediqnct W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection

  • Shrawan

    Hello sir, I’m trying to add some extra field in register like gender and phone. but I am getting some error. I added extra codes in both files, database and studio. but still only your fields are uploading and extra aren’t. so please help me…
    Value <br of type java.lang.String cannot be converted to JSONObject

  • Muhd Firdaus

    Hi admin,
    I already do what you give in this article one by one.
    All of it has no problem except;
    after I fill up all the required fields, and then I click the button = The App crashed.

    Try another phone still get same result.

  • Muhd Firdaus

    Hi admin, got this error. What does that mean?

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

  • vidhya

    hi sir,
    the app works fine on my emulator. but its not working on my device. a blank toast shows. both device connected on same wifi address. what to do?please reply sir.

    • You can debug it by opening the ip address in your mobile chrome browser and check. If it opens, the app is connected to your PC via wifi otherwise debug accordingly.

      • vidhya

        thank u sir..
        Working on my device by turning off firewall of my system

        • Great!

          • vidhya

            thank you very much for your valuable support.
            in my app i want to get users profile photo and display the photo in users account.
            how can i save the photo to database and retrieving the same?

          • Adi

            I thought there were issues with volley but it was windows firewall. 🙂

  • Anil Thakur

    I want to know where does rest api code used ? Actually i did the php part only and skipped andriod part from your post . And generate a query string to hit from android developer side .Everything is fine i am registering the user by using query string as well as login the user with database details. But i am confused about rest api coding , unable to find api coding . PLease help by replying asap .Thanks

  • John Vincent Batalla

    Hello Sir. I’m a beginner but I made sure to follow every steps here in this tutorial. but I have an error in the login. I think it is between SQLITEHANDLER and LoginActivity. please help. TIA https://uploads.disquscdn.com/images/7ad94bff13204ad31239a3bb38f3cbe106a3b7fc5630855aaf9a0daf832e2041.png

    • The url you are accessing is not accessible via your phone or the PHP code is not producing valid JSON. Debug accordingly. Open the URL in Postman and check.

    • Marc McCabe

      I also have this error. JSON object is being returned from the webserver but something is inserting the php filenames in the response variable before the JSON object.
      Like this (from logcat) ….
      “D/Volley: Login Response: login.php
      DB_Connect.php
      Config.php
      {“error”:true,”error_msg”:”User does not exist or password is incorrect. Please try again!”}”

      Not sure how to stop response from containing the filenames. I can’t find what is adding them into the response.

  • NG Miow

    Hi,very thankyou for the great tutorial
    May I ask is it have to create database on SQLiteOpenHelper every time before I can call the data out(to display on screen)?
    Can I just call some data straightly from phpmyadmin?

  • Abie Algiffary

    Hi admin, is this Works too if i use XAMPP and Mysql rather than WAMP and sqlite? Thank you

  • Anony Boy

    Wamp Server Login Work fine but my hostgator hosting not work black toast show ? how to fix it ?

  • CreativeZ StudioZ

    How to test the REST Api using POSTMAN . While i am checking your api
    ({“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”})
    This is the output
    Thanks in Advance

    • You need to user proper HTTP method (POST) and make sure that you are sending the params like email, password..

  • Nirmal Kumar

    Hi ravi
    login password is not matched even password is correct.It shows credentials are wrong.Encrypted password is not matching with actual password while login

  • Michael Keller
  • Innovative iliyas

    I think in your service response starting with JSONObject so, you have to request code from JSONObjectRequest then you will get the response, otherwise it won’t get the response.
    First of all you have to see which is object and which is array response,if you know these difference you can bind the restful services easily.
    Thank you.

  • Oumayma

    Hello, when I finally run the code I get the following error:
    09-07 16:38:56.177 18947-19240/com.example.userpc.androidhive E/Volley: [476449] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.1.162:80/userdb/register.php
    09-07 16:38:56.179 18947-18947/com.example.userpc.androidhive E/RegisterActivity: Registration Error: null
    09-07 16:38:56.298 18947-18947/com.example.userpc.androidhive E/ViewRootImpl: sendUserActionEvent() returned.

    when i open the link “com.example.userpc.androidhive”, get:
    {“error”:true,”error_msg”:”Required parameters (name, email or password) is missing!”}

  • Paramdeep Singh

    Hi sir, when I tried to run the code nothing has happened. When I clicked on registrer button it shows progress bar and after that no response from server or from application. I copy paste your exact code and changed database name, pwd, username(root).Nothing in logcat. But when I test register.php file in 000webhost server it shows the message :

    Warning: require_once(include/DB_Functions.php): failed to open stream: No such file or directory in /storage/ssd3/129/4044129/public_html/gwydion/register.php on line 3

    Fatal error: require_once(): Failed opening required ‘include/DB_Functions.php’ (include_path=’.:/usr/share/pear:/usr/share/php’) in /storage/ssd3/129/4044129/public_html/gwydion/register.php on line 3

    can you help me.

    • Paramdeep Singh

      I got an exception => Value <br of type java.lang.String cannot be converted to JSONObject

  • Droo the Furious

    Hello, first of all thank you for good tutorial but I’m very curious about how does the “StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener() {” get the login parameters? I see there’s a getParams method but it’s not called anywhere? Shouldn’t it be like this: ”
    StringRequest(Method.POST, AppConfig.URL_LOGIN, getParams(), new Response.Listener() {“?

  • John Paul Lim Gabule

    Thank you for this amazing solution. I find some error but I solve it anyway. Thank you and God Bless

    • You are welcome John.

      I wish you the same:)

  • Robert Košir

    Dear, when I try to save some data to my server I get the following error: Uncaught Error: Call to undefined method mysqli_stmt::get_result() when trying to storeUser, can anyone help?

  • Michael Keller

    Hi, I would like to know how to find the database of an image for the user profile and display it in an ImageView. That would be interesting, would you help me?

  • 이예진

    Hi sir, I followed your tutorial and there were a few bugs while build it but I found the resolutions. Your tutorial is amazing and easy to follow. However there’s a problem while running the app. I already tested php part with postman and it worked fine, however it doesn’t work when I’m using the app. Whenever I registered/logined, the toast message came up saying “java.netConnectException: failed to connect to 192.169.0.102 (port 80) after 5000ms: is Connectedfailed: EHOSTUNREACH (No route to host).” I guess 192.169.0.102 is android client’s ip address. Thanks in advance.

  • sarath

    hi ravi i am sarath i have problem in my android code how to connect swagger link with app please send code

  • sarath

    please send its urgent brother

  • sarath

    reply bro

  • Abdul Rehman

    Hello sir,

    Thank you for such a nice tutorial. You made my day. All the things mentioned in the post are as it is working just need to take a bit effort to resolve some minor error otherwise its working like charm.

  • Ashkan

    hi ravi. than for your tut

    When I click the register button, I get Connection Refused error in my logs.

    My login and register localhost IP is : 127.0.0.1. I searched many
    websites and articles and they wrote >> you should change
    127.0.0.1 to 10.0.2.2 but finally I didn’t succeed. My emulator is Nox
    player.
    i dont know what can i do ? pls help me