MySQL and Android Studio Example

Hi All,

I going to show on how to develop a mobile app that can insert the data to mySQL database. The server that I used is XAMPP server.

The mobile app is like below. It used to register the user like name, username and password. Then, it can be used as login account.

Hopefully, you enjoyed it !!!

           

This is when the user have registered.

Step 1 : Create a mySQL database in phpMyAdmin

  • Create a database named “students“.
  • Create a table named list with three column which is “id” , “name” , “username”  and “password“.
  • You can refer to my previous tutorial on how to create a database and table.

Create mySQL datatabase & table – XAMPP

Step 2 : Create 3 php files

  • Create a php file named conn.php.
<?php

$servername = "localhost";
$username = "root";
$password = "";
$database = "students";

// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);


?>
  • Create a php file named insertData.php. Then write coding below. You can test your php by put dummy value for name, user_name and password. Don’t forget to comment the variable $name, $user_name and $password.
<?php
require "conn.php";
$name = $_POST["name"];
$user_name = $_POST["user_name"];
$password = $_POST["password"];
//$name = "shaharil";
//$user_name = "shah";
//$password = "1234";

$mysqli_query = "INSERT INTO list VALUES (NULL,'$name','$user_name','$password');";

$result = mysqli_query($conn,$mysqli_query);

//RESET the AUTOINCREMENT
$result = mysqli_query($conn,"SET @num := 0;");
$result = mysqli_query($conn,"UPDATE list SET id = @num := (@num+1)");
$result = mysqli_query($conn,"ALTER TABLE list AUTO_INCREMENT =1");

if($result){
print("Your have registered!"); 
}
else{
print("NOT Successful"); 
}

?>
  • Create another php file named validateData.php. Then write coding below. You can test your php by put dummy value for user_name and password. Don’t forget to comment the variable $user_name and $password.
<?php

require "conn.php";
$user_name = $_POST["user_name"];
$password = $_POST["password"];
//$user_name = "shah";
//$password = "1234";

$mysqli_query = "SELECT * FROM list where username like '$user_name' and password like '$password'";

$result = mysqli_query($conn,$mysqli_query);

if(mysqli_num_rows($result)>0){
//print("Login success");
$row = mysqli_fetch_assoc($result); 
$name =$row["name"]; 
Print("Login Successful..Welcome ".$name);

}
else{
print("Login not succes"); 
}

?>

Step 3 : Components should have in Android Studio

  • You project need to have all files like below. The gradle file not change.

Step 4 : Design the activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="username"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText1" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="password"
        android:inputType="textPersonName"
        app:layout_constraintStart_toStartOf="@+id/editText2"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Register"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText3" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:ems="10"
        android:hint="username"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword"
        app:layout_constraintStart_toStartOf="@+id/editText4"
        app:layout_constraintTop_toBottomOf="@+id/editText4" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText5" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 5 : Create a class named Design the BackgroundWorker.java:

package com.example.a06_mysql_reg_login;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker(Context ctx){
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String login_url = params[0];
        String type = params[1];
        String name = params[2];
        String username = params[3];
        String password = params[4];
            try {

                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                String post_data = "";
                if(type.equals("register")) {
                    post_data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&"
                            + URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8")+ "&"
                            + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
                }
                else if(type.equals("login")){
                    post_data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
                            + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
                }

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {

        alertDialog.setMessage(result);
        alertDialog.show();
        //Toast.makeText(context.getApplicationContext(),result,Toast.LENGTH_LONG).show();

    }
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

Step 6 : Write the code in MainActivity.java:

package com.example.a06_mysql_reg_login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText nameRegister;
    EditText usernameRegister;
    EditText passwordRegister;
    Button register;

    EditText usernameLogin;
    EditText passwordLogin;
    Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameRegister = findViewById(R.id.editText1);
        usernameRegister = findViewById(R.id.editText2);
        passwordRegister = findViewById(R.id.editText3);
        register = findViewById(R.id.button1);

        usernameLogin = findViewById(R.id.editText4);
        passwordLogin = findViewById(R.id.editText5);
        login = findViewById(R.id.button2);


        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameRegister.getText().toString();
                String username = usernameRegister.getText().toString();
                String password = passwordRegister.getText().toString();
                String url = "http://192.168.43.41/ArinProject/ANDROID_MYSQL/insertData.php";
                String type = "register";
                BackgroundWorker backgroundWorker = new BackgroundWorker(MainActivity.this);
                backgroundWorker.execute(url,type,name,username,password);
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameRegister.getText().toString();
                String username = usernameLogin.getText().toString();
                String password = passwordLogin.getText().toString();
                String url = "http://192.168.43.41/ArinProject/ANDROID_MYSQL/validateData.php";
                String type = "login";
                BackgroundWorker backgroundWorker = new BackgroundWorker(MainActivity.this);
                backgroundWorker.execute(url,type,name,username,password);
            }
        });

    }
}

Step 7 : You can test you app

DONE !!!

Don’t forget to set your PC localhost be able to access by mobile phone. Please look on my previous tutorial here:

Access PC Localhost (XAMPP Server) from Mobile Phone