Android Login Registration using PHP and MySQL

Android Login Registration using PHP and MySQL

Hey Technoz! In this tutorial, we are going to see how to build android login registration app using PHP and MySQL as a back end system. You can use any other language and database as a back end. But, as PHP and MySQL are most common and popular, we will be using it in this tutorial. This Android Login Registration using PHP and MySQL tutorial covers creating a new user registration, Logging in already registered student, and logging out also. So lets start.

Creating Server side

In our project, the app will be a client sending requests to the server and the PHP files and database will act as a back end server. Thus we are creating two parts in our android login registration tutorial.

Creating Database

Obviously, we first need a database to store and retrieve data. So create a database and table users in it. The table contains fields as id, username, email and password. You can use the following SQL query.

DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

Creating PHP Files

Of course, we need a separate php file to establish a connection with the database. So create file config.php and paste the code below in it.

<?php
$conn = new mysqli("localhost", "root", "", "newdb");

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//echo "Connected successfully";
?>

Remember to change the connection values with yours.

Now, we will create a separate file which does the working of logging in the user. Thus create a file login.php with the following code.

<?php
include "config.php";

$response = array();
if($_POST['email'] && $_POST['password']){
	$email = $_POST['email'];
	$post_password = $_POST['password'];
	$stmt = $conn->prepare("SELECT username, password FROM users WHERE email = ?");
	$stmt->bind_param("s",$email);
	$stmt->execute();
	$stmt->bind_result($username, $db_password);
	$stmt->fetch();
	if(password_verify($post_password, $db_password)){
		$response['error'] = false;
		$response['message'] = "Login Successful!";
		$response['email'] = $email;
		$response['username'] = $username;
	} else{
		$response['error'] = false;
		$response['message'] = "Invalid Email or Password";
	}
} else {
	$response['error'] = true;
	$response['message'] = "Insufficient Parameters";
}
echo json_encode($response);	
?>

As the android login registration app requires data in JSON format, we are using an array here. At first, we will receive the POST variables and check if the user exists in database and perform a password verification. If the credentials are right, we will put the success message in array variable. Lastly, we will echo the array as a JSON response.

Now its time for a registration task. Similarly, we will create a php file register.php with the following code in it.

<?php
include "config.php";

$response = array();
if($_POST['email'] && $_POST['password'] && $_POST['username']){
	$email = $_POST['email'];
	$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
	$username = $_POST['username'];
	$sql = $conn->prepare("SELECT * FROM users WHERE email = ?");
	$sql->bind_param("s",$email);
	$sql->execute();
	$sql->store_result();

	if($sql->num_rows > 0){
		$response['error'] = false;
		$response['message'] = "User already registered";
	} else{
		$stmt = $conn->prepare("INSERT INTO `users` (`username`, `email`, `password`) VALUES(?,?,?)");
		$stmt->bind_param("sss", $username, $email, $password);
		$result = $stmt->execute();
		if($result){
			$response['error'] = false;
			$response['message'] = "User Registered Successfully";
		} else {
			$response['error'] = false;
			$response['message'] = "Cannot complete user registration";
		}
	}
} else{
	$response['error'] = true;
	$response['message'] = "Insufficient Parameters";
}
echo json_encode($response);	
?>

Similar to the login file, we have created the above file for registration task. Here we are accepting username, email and password as a POST parameters. As usual, we are inserting the received data in the database with password encrypted. The success/failure message is sent using array variables as a JSON response.

Thus, we have completed the server side part. Now we will move towards the client side android app in android login registration.

Creating Client side

Now we have to build an android app which will take the values entered by user, send it to specific urls, get back the results and show to the user. So lets start.

We will be using http requests to send/receive data. For that purpose, we need to add the below line in app-level build.gradle file.

useLibrary 'org.apache.http.legacy'

Furthermore, we need to add the internet permission in AndroidManifest.xml file as follows.

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

Note: In this post, we are using a custom classes to make api call and retrieve data, which is a time consuming and a little glitch process. There is better way to do this with Retrofit library, where the call is secure, requires less code and is a recommended way. Must check the updated Retrofit Library tutorial with RecyclerView in Kotlin post to learn the recommended way.

 

At first, we will build a special class which will accept the URLs and POST data parameters, send them to their respective places, and return the results received. So create a new java class RequestHandler.java with following code in it.

package net.softglobe.tutorials;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Belal on 9/5/2017.
 */

public class RequestHandler {


    //this method will send a post request to the specified url
    //in this app we are using only post request
    //in the hashmap we have the data to be sent to the server in keyvalue pairs
    public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
        URL url;

        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;

                while ((response = br.readLine()) != null) {
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    //this method is converting keyvalue pairs data into a query string as needed to send to the server
    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

The method sendPostRequest() accepts the url and post parameters. We are using a HashMap data structure here to get and set key and value pairs. We are here building a string using StringBuilder class and append the response received, to the string. The method getPostDataString() accepts HashMap parameters and appends them with the url.

Creating Activities

Registration Activity

Now, we will create the registration activity. Create a new empty activity and write below code in activity_register.xml file.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="10sp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Registration Screen"
            android:gravity="center_horizontal"
            android:textSize="20sp"/>
        <EditText
            android:id="@+id/ed_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Username"/>
        <EditText
            android:id="@+id/ed_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"/>
        <EditText
            android:id="@+id/ed_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="password"
            android:inputType="textPassword"/>
        <Button
            android:onClick="register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login Here"
            android:onClick="login"
            android:gravity="center_horizontal"/>
    </LinearLayout>
</ScrollView>

We have created three EditText for username, email, password and a submit button for android login registration. See the image below.

Android Login Registration using PHP and MySQL

Now lets build the file RegisterActivity.java as follows.

package net.softglobe.tutorials;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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

import java.util.HashMap;

public class RegisterActivity extends AppCompatActivity {

    EditText ed_username, ed_email, ed_password;
    public static final String URL_REGISTER = "http://192.168.43.17/login-register/register.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        ed_username = findViewById(R.id.ed_username);
        ed_email = findViewById(R.id.ed_email);
        ed_password = findViewById(R.id.ed_password);
    }

    public void register(View view){
        final String username = ed_username.getText().toString();
        final String email = ed_email.getText().toString();
        final String password = ed_password.getText().toString();

        if(username.isEmpty() || email.isEmpty() || password.isEmpty()){
            Toast.makeText(this, "Please fill all the fields", Toast.LENGTH_SHORT).show();
        }

        else {
            class Login extends AsyncTask<Void, Void, String> {
                ProgressDialog pdLoading = new ProgressDialog(RegisterActivity.this);

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                    //this method will be running on UI thread
                    pdLoading.setMessage("\tLoading...");
                    pdLoading.setCancelable(false);
                    pdLoading.show();
                }

                @Override
                protected String doInBackground(Void... voids) {
                    //creating request handler object
                    RequestHandler requestHandler = new RequestHandler();

                    //creating request parameters
                    HashMap<String, String> params = new HashMap<>();
                    params.put("email", email);
                    params.put("password", password);
                    params.put("username", username);

                    //returing the response
                    return requestHandler.sendPostRequest(URL_REGISTER, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    pdLoading.dismiss();

                    try {
                        //converting response to json object
                        JSONObject obj = new JSONObject(s);
                        //if no error in response
                        if (!obj.getBoolean("error")) {
                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(RegisterActivity.this, "Exception: " + e, Toast.LENGTH_LONG).show();
                    }
                }
            }

            Login login = new Login();
            login.execute();
        }
    }

    public void login(View view){
        finish();
        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
        startActivity(intent);
    }
}

The above class takes the values entered from user and the values are sent to the sendPostRequest method in the RequestHandler class. The RequestHandler class then does the work of sending and receiving data and we print the response message by toast text. We do this process using AsyncTask which helps to do things in background. You can learn more about AsyncTask Here. The values entered by user will be stored using PHP and MySQL database.

Login Activity

Furthermore, we move towards the LoginActivity. At first, create layout using activity_login.xml file with the following code in it.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="10sp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login Screen"
            android:gravity="center_horizontal"
            android:textSize="20sp"/>
        <EditText
            android:id="@+id/ed_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"/>
        <EditText
            android:id="@+id/ed_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="password"
            android:inputType="textPassword"/>
        <Button
            android:onClick="login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register Here"
            android:gravity="center_horizontal"
            android:onClick="register"/>
    </LinearLayout>
</ScrollView>

Above file will create two EditText input fields for email and password and a submit button as shown below.

Android Login Registration using PHP and MySQL

Lets have a look at java file LoginActivity.java below for android login registration tutorial.

package net.softglobe.tutorials;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

    public static final String URL_LOGIN = "http://192.168.43.17/login-register/login.php";
    EditText ed_email, ed_password;
    SharedPreferences sharedPreferences;
    public static final String MY_PREFERENCES = "MyPrefs";
    public static final String EMAIL = "email";
    public static final String STATUS = "status";
    public static final String USERNAME = "username";
    private boolean status;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ed_email = findViewById(R.id.ed_email);
        ed_password = findViewById(R.id.ed_password);

        sharedPreferences = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);

        status = sharedPreferences.getBoolean(STATUS, false);

        if (status){
            finish();
            Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
            startActivity(intent);
        }
    }

    public void login(View view){
        final String email = ed_email.getText().toString();
        final String password = ed_password.getText().toString();

        if(email.isEmpty()|| password.isEmpty()){
            Toast.makeText(this, "Please fill all the fields", Toast.LENGTH_SHORT).show();
        }

        else {
            class Login extends AsyncTask<Void, Void, String> {
                ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                    //this method will be running on UI thread
                    pdLoading.setMessage("\tLoading...");
                    pdLoading.setCancelable(false);
                    pdLoading.show();
                }

                @Override
                protected String doInBackground(Void... voids) {
                    //creating request handler object
                    RequestHandler requestHandler = new RequestHandler();

                    //creating request parameters
                    HashMap<String, String> params = new HashMap<>();
                    params.put("email", email);
                    params.put("password", password);

                    //returing the response
                    return requestHandler.sendPostRequest(URL_LOGIN, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    pdLoading.dismiss();

                    try {
                        //converting response to json object
                        JSONObject obj = new JSONObject(s);
                        //if no error in response
                        if (!obj.getBoolean("error")) {
                            String username = obj.getString("username");

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString(USERNAME, username);
                            editor.putString(EMAIL, email);
                            editor.putBoolean(STATUS, true);
                            editor.apply();

                            finish();
                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(LoginActivity.this, "Exception: " + e, Toast.LENGTH_LONG).show();
                    }
                }
            }

            Login login = new Login();
            login.execute();
        }
    }

    public void register(View view){
        finish();
        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(intent);
    }
}

Similar to the Login file, we are taking input values from user and sending them using RequestHandler class. The server side php scripts will check for valid credentials and return the results. If the result is true, we will open a new welcome activity. Here, we are taking care that once the user is logged in, he/she will not need to login again. For this purpose, we are here using SharedPreferences data structure. It is a key-value paired data structure which stores the small amount of data in them.

Note: In the above code, you have to replace the ip address in URL_LOGIN to your own PC’s ip. To find ip address, open command prompt and type “ipconfig” and press enter. You will see “IPv4 Address”, that is your ip. Copy it and replace in the URL_LOGIN with your ip address. Your PC should be connected to the internet for the ip address to work. This is a mandatory thing and the app won’t work unless this is set carefully.

Welcome Activity

After fetching the data we will store it in SharedPreferences. The ‘status’ key contains a Boolean value which will set  to 1 after successful login. The next time user will open the LoginActivity, he/she will be directly redirected to the Welcome screen. We are also storing the email, username and password after login. Now lets create a new activity WelcomeActivity which will open only after successful login. Below code of activity_welcome.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_margin="10sp">

    <TextView
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:text="Welcome, "/>

    <Button
        android:id="@+id/logout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Logout"/>

</LinearLayout>

The java code of WelcomeActivity.java in Android Login Registration using PHP and MySQL tutorial is as follows.

package net.softglobe.tutorials;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class WelcomeActivity extends AppCompatActivity {

    SharedPreferences sharedPreferences;
    public static final String MY_PREFERENCES = "MyPrefs";
    public static final String USERNAME = "username";
    TextView username;
    Button logout;

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

        sharedPreferences = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
        username = findViewById(R.id.username);
        username.setText("Welcome, " + sharedPreferences.getString(USERNAME,""));

        logout = findViewById(R.id.logout);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear();
                editor.apply();
                finish();
                Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }
}

We are showing here username of candidate and a logout button. Obviously, the logout button will clear all the values in SharedPreferences and redirect user to the login screen. See the screenshot below.

Android Login Registration using PHP and MySQL

Thus, we have completed the Android Login Registration using PHP and MySQL tutorial. Hope you understand it. Furthermore, if you have any doubts, feel free to ask in comment below. You can always download the source code from below link.

Download Source Code

If you want to publish this app and host the contents live, then you can have a look at Web hosting guide. I recommend using Hostinger Hosting Services as they are cheap and best in class. Clik on the banner below to learn more.

14 thoughts on “Android Login Registration using PHP and MySQL

  1. Akinyemi john says:

    Hi
    A good tutorial you have here but i have questions see below
    Is there a way to prevent a user from using another persons
    crdentials i.e preventing user A from using user B credentials on his device unless he registers. Is there a way
    to make the username or email or password to be used only once. If the user B wants to use user A username or email or password
    the app should prompt or show dialog “username or email or password already in use by another user”. Kindly help

    1. Ashish Joshi says:

      Good idea. Yes we can do it by setting a boolean value after logging in and should not permit another user to login unless this flag is unset. We will unset the flag only after user loggs out from device.

    1. d
      datapalace2019 says:

      the code below is what you need to edit
      public static final String URL_LOGIN = “http://192.168.43.17/login-register/login.php”;

      change the IP to yours but make sure you dnt replace the IP with “localhost”

      Open the Command Prompt by clicking Start and search CMD then click cmd.exe.
      Type ipconfig /all

      the above list IPs, locate IP like 192.168..

      then the problem is solved

  2. S
    Sandeep says:

    HI sir , it is showing error org.json.jsonexception end of input at character 0 of, im using not import androidx.appcompat.app.AppCompatActivity; not import android.support.v7.app.AppCompatActivity;

    Please advice me how to solve this?.

    1. S
      Sandeep says:

      * i’m using import androidx.appcompat.app.AppCompatActivity; not import android.support.v7.app.AppCompatActivity;

  3. d
    datapalace2019 says:

    Thanks so much. I was able to submit to database but the TOAST is returning error

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

    Please what am i getting wrong? what is needed to correct this.

    Thanks once again

  4. d
    datapalace2019 says:

    Never Mind, Ive solved this by putting off error report in my PHP serveride script.

    I put error_reporting(0) at the top of login.php and regiser.php.

    I am really enjoying your tutorials. Maybe i will come and visit you in India for more tutorial. Smiles..

    Kudos.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.