Hay guys pada tutorial kali ini, saya akan coba membuat contoh aplikasi android dengan database mysql. Nahhh.. untuk menghubungkan app android dengan mysql saya menggukan PHP sebagai API.

Tutorial ini melanjutkan tutorial sebelumnya, yang membahas mengenai macam-macam library untuk data networking, atau komunikasi HTTP di aplikasi android. sekarang saya coba menggunakan salah satu dari library tersebut. untuk contoh ini saya pake volley library.

Langsung saja buka android studio dan buat projeck baru,

Kemudian pilih tambahkan volley library sebagai modul, pilih File-New-Import Module

setelah volley library ditambahkan, jangan lupa tambahkan di build.gradle-dependencies, seperti dibawah ini

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile project(':volley')
    compile 'com.android.support:design:23.4.0'
}

Lanjut pembuatan activity dan layout, saya hanya membuat satu layout saja, digunakan untuk register dan login. Tapi yang penting esensi dari tutorial ini tersampaikan.

pada layout activity_main.xml tambahkan code berikut,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/padding_medium"
    tools:context="nt.volley.project.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputLayoutName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/name"
            android:inputType="text"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="11dp"
        tools:layout_editor_absoluteY="16dp"
        android:layout_marginTop="@dimen/margin_medium"
        android:layout_below="@id/textInputLayoutName"
        android:id="@+id/textInputLayoutEmail">

        <EditText
            android:id="@+id/etEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/email"
            android:inputType="textEmailAddress" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textInputLayoutEmail"
        android:layout_marginTop="@dimen/margin_medium"
        android:id="@+id/textInputLayoutPassword">

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:inputType="textPassword" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textInputLayoutPassword"
        android:layout_marginTop="@dimen/margin_long"
        android:text="@string/login" />

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnLogin"
        android:layout_marginLeft="22dp"
        android:layout_marginStart="22dp"
        android:layout_toEndOf="@+id/btnLogin"
        android:layout_toRightOf="@+id/btnLogin"
        android:text="@string/register" />

</RelativeLayout>

Setelah itu buka class MainActivity.java, dan tambahakn code seperti dibawah ini,

package nt.volley.project;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

public class MainActivity extends AppCompatActivity implements OnClickListener {

    private static final String TAG = "MainActivity";
    private EditText etName;
    private EditText etEmail;
    private EditText etPassword;
    private Button btnLogin;

    private RequestQueue requestQueue;

    String REGISTER_URL = "http://10.0.2.2/login/register.php";
    String LOGIN_URL = "http://10.0.2.2/login/login.php";
    private Button btnRegister;


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

        etName = (EditText) findViewById(R.id.etName);
        etEmail = (EditText) findViewById(R.id.etEmail);
        etPassword = (EditText) findViewById(R.id.etPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);

        // deklarasi variabel dari kelas volley
        requestQueue = Volley.newRequestQueue(this);
    }

    @Override
    public void onClick(View v) {
        // Kondisi ketika button diklik, klik register atau login

        if (v == btnRegister){
            // mengambil data dari form
            String name = etName.getText().toString();
            String email = etEmail.getText().toString();
            String password = etPassword.getText().toString();

            // memanggil fungsi register dengan mengisi parameter yang dibutuhkan
            register(name, email, password);
        }
        if (v == btnLogin){
            // mengambil data dari form
            String email = etEmail.getText().toString();
            String password = etPassword.getText().toString();

            // memanggil fungsi login dengan mengisi parameter email dan password
            login(email, password);
        }
    }

    // Fungsi login dengan menggunakan volley library
    private void login(String email, String password) {

        // mengisi parameter
        JSONObject params = null;
        try{
            params = new JSONObject();
            params.put("email", email);
            params.put("password", password);
        }catch (JSONException e){
            e.printStackTrace();
        }

        // handle respon dari eksekusi api
        Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // kondisi jika ada respon dari api
                try {
                    // parsing data dari hasil eksekusi dalam bentuk json
                    boolean error = response.getBoolean("error");
                    Log.d(TAG, "Error : "+error);
                    // dilakukan pengecekan, jika pesar error false maka berhasil
                    if (!error) {
                        // parsing data json
                        JSONObject user = response.getJSONObject("user");
                        int kode = response.getInt("kode");
                        String name = user.getString("name");
                        String email = user.getString("email");

                        // menampilkan data
                        Toast.makeText(getApplication(), "Selamat login berhasil : name : "+name+" and email : "+email+" and kode : "+kode,Toast.LENGTH_LONG).show();
                    }else{
                        // kondisi respon error
                        String error_message = response.getString("error_msg");
                        Toast.makeText(getApplication(), error_message,Toast.LENGTH_SHORT).show();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // kondisi tidak ada respon dari api
                Toast.makeText(getApplication(), error.getMessage(),Toast.LENGTH_SHORT).show();
            }
        };

        /*pemanggilan fungsi untuk request api, dengan mengisikan method POST, URL, parameter, listener, dan errorListener*/
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,LOGIN_URL, params,listener, error);
        Log.d(TAG, request.getUrl());
        Log.d(TAG, params.toString());
        // memasukan request ke antrian eksekusi
        requestQueue.add(request);
    }

    // fungsi register dengan volley library
    private void register(String name, String email, String password) {
        // pengisian parameter yang akan disimpan pada database
        JSONObject params = null;
        try{
            params = new JSONObject();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);
        }catch (JSONException e){
            e.printStackTrace();
        }


        Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    boolean error = response.getBoolean("error");
                    Log.d(TAG, "Error : "+error);
                    if (!error) {
                        JSONObject user = response.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        Toast.makeText(getApplication(), "Selamat registrasi berhasil : name : "+name+" and email : "+email,Toast.LENGTH_LONG).show();
                    }else{
                        String error_message = response.getString("error_msg");
                        Toast.makeText(getApplication(), error_message,Toast.LENGTH_SHORT).show();
                    }


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

            }
        };
        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplication(), error.getMessage(),Toast.LENGTH_SHORT).show();
            }
        };

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,REGISTER_URL, params,listener, error);
        Log.d(TAG, request.getUrl());
        Log.d(TAG, params.toString());

        requestQueue.add(request);

    }
}

Jangan lupa tambahkan permission INTERNET supaya aplikasi dapat berkomunikasi melalui jaringan.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nt.volley.project" >

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Pembuatan aplikasi android selesai. Langkah selanjutnya pembuatan database di PhpMyadmin dan buat satu tabel dengan nama tb_login,

CREATE TABLE `tb_login` (
 `kode` int(11) NOT NULL,
 `name` varchar(150) NOT NULL,
 `email` varchar(100) NOT NULL,
 `password` varchar(50) NOT NULL,
 `salt` varchar(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Langkah terakhir membuat API dengan menggunakan PHP,

buat file Conf.php

<?php
 
/**
 * Database config variables
 */
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "db_login");
?>

DB_Connect.php

<?php
class DB_Connect {
 private $conn;
 
 // Connecting to database
 public function connect() {
 require_once 'Conf.php';
 
 // Connecting to mysql database
 $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
 
 // return database handler
 return $this->conn;
 }
}
 
?>

selanjutnya buat file DB_Functions.php untuk fungsi simpan data, pemanggilan data, dan beberapa fungsi validasi.

<?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) {
 $hash = $this->hashSSHA($password);
 $encrypted_password = $hash["encrypted"]; // encrypted password
 $salt = $hash["salt"]; // salt
 
 $stmt = $this->conn->prepare("INSERT INTO tb_login(name, email, password, salt) VALUES(?, ?, ?, ?)");
 $stmt->bind_param("ssss", $name, $email, $encrypted_password, $salt);
 $result = $stmt->execute();
 $stmt->close();
 
 // check for successful store
 if ($result) {
 $stmt = $this->conn->prepare("SELECT * FROM tb_login 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 tb_login WHERE email = ?");
 
 $stmt->bind_param("s", $email);
 
 if ($stmt->execute()) {
 $user = $stmt->get_result()->fetch_assoc();
 $stmt->close();
 
 $salt = $user['salt'];
 // verifying user password
 $encrypted_password = $user['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 tb_login 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;
 }
 
}
 
?>

buat file login.php

<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();

header('Content-Type: application/json');
// json response array
$response = array("error" => FALSE);
$json = file_get_contents('php://input');
$obj = json_decode($json);
$email = $obj->{'email'};
$password = $obj->{'password'};


if ($email !== null && $password !== null) {
 
 
 // get the user by email and password
 $user = $db->getUserByEmailAndPassword($email, $password);
 
 if ($user != false) {
 // use is found
 $response["error"] = FALSE;
 $response["kode"] = $user["kode"];
 $response["user"]["name"] = $user["name"];
 $response["user"]["email"] = $user["email"];
 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);
}
?>

register.php

<?php
 
require_once 'DB_Functions.php';
$db = new DB_Functions();
 
header('Content-Type: application/json');
// json response array
$response = array("error" => FALSE);



$json = file_get_contents('php://input');
$obj = json_decode($json);
$name = $obj->{'name'};
$email = $obj->{'email'};
$password = $obj->{'password'};
 
if ($name !== null && $email !== null && $password !== null) {
 
 // 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["user"]["name"] = $user["name"];
 $response["user"]["email"] = $user["email"];
 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);
}
?>

Oke…tutorial membuat login dan register dengan menggunakan volley library telah selesai, untuk contoh project-nya bisa di download di github https://github.com/ntyazid/Sample-Project-Volley

Sekian, dan sampai jumpa ditutorial berikutnya… 🙂

Referensi :

  1. https://www.androidhive.info

Leave a Reply

Your email address will not be published. Required fields are marked *