Code Example

Android Volley PHP MySQL Register/Login Snippets

Learn about how to implement registration and login targeting PHP MySQL backend, with Volley as the HTTP Client.

1. Android PHP MYSQL Register Login Volley Example

A simple step by step Android PHP MySQL Registeration and Login code example with Volley.

This is a simple PHP MySQL Registeration and Login code snippets. The HTTP client used is Volley.

This example will comprise the following files:

  • LoginActivity.java
  • Welcome.java

Step 1: Write PHP code

Create the following PHP files and add code as showb below:

(a). config.php

<?php

define('hostname', 'localhost');
define('user', 'root');
define('password', '');
define('db_name', 'tutorial2');

?>

(b). connection.php

<?php

    require_once 'config.php';

    class DB_Connection {

        private $connect;
        function __construct() {
            $this->connect = mysqli_connect(hostname, user, password, db_name)
            or die("Could not connect to db");

        }

        public function getConnection()
        {
            return $this->connect;
        }
    }

?>

(c). user_control.php

<?php

include_once 'connection.php';

    class User {

        private $db;
        private $connection;

        function __construct() {
            $this -> db = new DB_Connection();
            $this -> connection = $this->db->getConnection();
        }

        public function does_user_exist($email,$password)
        {
            $query = "Select * from users where email='$email' and password = '$password' ";
            $result = mysqli_query($this->connection, $query);
            if(mysqli_num_rows($result)>0){
                $json['success'] = ' Welcome '.$email;
                echo json_encode($json);
                mysqli_close($this -> connection);
            }else{
                $query = "insert into USERS (email, password) values ( '$email','$password')";
                $inserted = mysqli_query($this -> connection, $query);
                if($inserted == 1 ){
                    $json['success'] = 'Acount created';
                }else{
                    $json['error'] = 'Wrong password';
                }
                echo json_encode($json);
                mysqli_close($this->connection);
            }

        }

    }

    $user = new User();
    if(isset($_POST['email'],$_POST['password'])) {
        $email = $_POST['email'];
        $password = $_POST['password'];

        if(!empty($email) && !empty($password)){

            $encrypted_password = md5($password);
            $user-> does_user_exist($email,$password);

        }else{
            echo json_encode("you must type both inputs");
        }

    }
?>

Step 2: Create Android Project

  1. Open your AndroidStudio IDE.
  2. Go to File-->New-->Project to create a new project.

Step 3: Dependencies

In your app/build.gradle add dependencies as shown below:

Add Volley 'com.mcxiaoke.volley as a dependency:

dependencies {
//..
    implementation 'com.mcxiaoke.volley:library:1.0.19'

}

Step 4: Design Layouts

*(a). activity_login.xml

Create a file named activity_login.xml and design it as follows:

Inside a LinearLayout add several EditTexts and Button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:gravity="center_horizontal"
    android:orientation="vertical"  tools:context=".LoginActivity">

    <EditText android:id="@+id/email" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="Email"
        android:inputType="textEmailAddress" android:maxLines="1"
        android:singleLine="true" />

    <EditText android:id="@+id/password" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:hint="@string/prompt_password"
        android:inputType="textPassword"
        android:maxLines="1" android:singleLine="true" />

    <Button android:id="@+id/sign_in_register"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_marginTop="16dp" android:text="SIGN IN OR REGISTER"
     />

</LinearLayout>

*(b). welcome_activity.xml

Create a file named welcome_activity.xml and design it as follows:

Then add a Button and TextView inside this layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="WELCOME"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LOGOUT"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Step 5: Write Code

Write Code as follows:

(a). LoginActivity.java

Create a file named LoginActivity.java

Here is the full code

package my.mysql_php_register_login;

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

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

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

public class LoginActivity extends AppCompatActivity {

    private EditText email,password;
    private Button sign_in_register;
    private RequestQueue requestQueue;
    private static final String URL = "http://192.168.1.65:80/tutorial2/user_control.php";
    private StringRequest request;

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

        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        sign_in_register = (Button) findViewById(R.id.sign_in_register);

        requestQueue = Volley.newRequestQueue(this);

        sign_in_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if(jsonObject.names().get(0).equals("success")){
                                Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getApplicationContext(),Welcome.class));
                            }else {
                                Toast.makeText(getApplicationContext(), "Error" +jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        HashMap<String,String> hashMap = new HashMap<String, String>();
                        hashMap.put("email",email.getText().toString());
                        hashMap.put("password",password.getText().toString());

                        return hashMap;
                    }
                };

                requestQueue.add(request);
            }
        });
    }
}

(b). Welcome.java

Create a file named Welcome.java

Here is the full code

package my.mysql_php_register_login;

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

public class Welcome extends Activity {

    private Button log_out;

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

        log_out = (Button) findViewById(R.id.button);
        log_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),LoginActivity.class));
            }
        });
    }
}

Run

Simply copy the source code into your Android Project,Build and Run.

Read More.