Selasa, 07 November 2017

Aplikasi Perpustakaan Berbasis CLient-Server

Assalamualaiqum Wr. Wb.
Kali ini saya akan menshare cara membuat aplikasi peminjaman buku di perpustakaan berbasis client-server, tapi saya akan mempostingnya secara bertahap. Jadi pantau terus blog saya :)
Yang pertama saya akan bahas adalah proses Login dan Registrasi akun. Ok langsung saja !
  1. Siapkan database, buat di PHPMyAdmin
  • Nama database “db_perpustakaan”
  • Nama tabel : “daftar_user”, “user”,”peminjaman”
Tabel  “daftar_user” berisi data registrasi user, “user” berisi data user yang terdaftar, sedangkan tabel “peminjaman” berisi data transaksi peminjaman buku.
  1. Buat file PHP sebagai servernya dengan nama folder “perpustakaan_server” dan simpan di C:\xampp\htdocs.
Berikut source codenya:
  • Koneksi.php
<?php
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'db_perpustakaan';
$koneksi = mysql_connect($server, $user, $pass) or die('Gagal Koneksi');
mysql_select_db($db) or die('Gagal Select Database');
?>

File koneksi ini berfungsi untuk konek ke database.
  • Index.php
<form method="POST" action="registrasi.php">
    <input type="text" name="nim" placeholder="nim"/> <br/>
    <input type="text" name="nama" placeholder="nama"/> <br/>
    <input type="text" name="tlp" placeholder="tlp"/> <br/>
   <input type="text" name="username" placeholder="username"/> <br/>
   <input type="password" name="password" placeholder="password"/><br/>
   <button type="submit">Simpan</button>
</form>

File index diatas merupakan form dari peminjaman buku.
  • Registrasi.php
<?php
include("koneksi.php");
$nim = $_POST["nim"];
$nama = $_POST["nama"];
$tlp = $_POST["tlp"];
$user = $_POST["username"];
$pass = $_POST["password"];
$hasil_simpan = mysql_query("INSERT INTO daftar_user (nim, nama, tlp)VALUES ('$nim','$nama', '$tlp')");
//simpan nilai dari id beserta user dan password
$hasil_id = mysql_query("INSERT INTO user (username, password) VALUES ('$user', '$pass')");
if ($hasil_simpan && $hasil_id) {
   echo 1;
} else {
   echo 0; }
 
File registrasi merupakan aksi dari penyimpanan data peminjam ke database.
  • User.php
<?php
include('koneksi.php');
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "SELECT * from user where username = '$user' and password = '$pass'";
$hasil = mysql_query($query) or die("Gagal Select Tabel");
if (mysql_num_rows($hasil) == 1) {
   echo 1;
} else {
   echo 0; }

File user merupakan aksi untuk mencocokkan data user yang di inputkan saat login di web dengan data di database.
  • Peminjaman.php
<?php
include("koneksi.php");
$nim = $_POST["nim"];
$nama = $_POST["nama"];
$judul = $_POST["judul"];
$tgl_pinjam = $_POST["tgl_pinjam"];
$tgl_kembali = $_POST["tgl_kembali"];
$jumlah = $_POST["jumlah"];
$hasil_simpan = mysql_query("INSERT INTO peminjaman (nim, nama, judul,tgl_pinjam,tgl_kembali,jumlah)VALUES ('$nim','$nama', '$judul','$tgl_pinjam','$tgl_kembali','$jumlah')");
File diatas merupakan aksi menyimpan data peminjaman ke database.
  1. Selanjutnya kita beralih ke eclipse-ADT. Buat project baru dengan nama “Perpustakaan”.
  • Buat activity baru dengan Klik New->Other->Android Activity. Beri nama CustomHttpClient yang merupakan koneksi ke server.
CustomHttpClient.java
package com.example.perpustakaan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
    public static final String URL = "http://192.168.100.62/perpustakaan_server/";
  /** The time it takes for our client to timeout */
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

   /** Single instance of our HttpClient */
   private static HttpClient mHttpClient;
   /**
    * Get our single instance of our HttpClient object.
    *
    * @return an HttpClient object with connection parameters set
    */
   private static HttpClient getHttpClient() {
       if (mHttpClient == null) {
           mHttpClient = new DefaultHttpClient();
           final HttpParams params = mHttpClient.getParams();
           HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
           HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
           ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
       }
       return mHttpClient;
   }
   /**
    * Performs an HTTP Post request to the specified url with the
    * specified parameters.
    *
    * @param url The web address to post the request to
    * @param postParameters The parameters to send via the request
    * @return The result of the request
    * @throws Exception
    */
   public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
       BufferedReader in = null;
       try {
           HttpClient client = getHttpClient();
           HttpPost request = new HttpPost(url);
           UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
           request.setEntity(formEntity);
           HttpResponse response = client.execute(request);
           in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

           StringBuffer sb = new StringBuffer("");
           String line = "";
           String NL = System.getProperty("line.separator");
           while ((line = in.readLine()) != null) {
               sb.append(line + NL);
           }
           in.close();

           String result = sb.toString();
           return result;
       } finally {
           if (in != null) {
               try {
                   in.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }      }  }   }
   /**
    * Performs an HTTP GET request to the specified url.
    *
    * @param url The web address to post the request to
    * @return The result of the request
    * @throws Exception
    */
   public static String executeHttpGet(String url) throws Exception {
       BufferedReader in = null;
       try {
           HttpClient client = getHttpClient();
           HttpGet request = new HttpGet();
           request.setURI(new URI(url));
           HttpResponse response = client.execute(request);
           in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
           StringBuffer sb = new StringBuffer("");
           String line = "";
           String NL = System.getProperty("line.separator");
           while ((line = in.readLine()) != null) {
               sb.append(line + NL);
           }
           in.close();
           String result = sb.toString();
           return result;
       } finally {
           if (in != null) {
               try {
                   in.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }   }   }  } }

    activity_daftar.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".RegistActivity"
   android:orientation="vertical" >
   <EditText
       android:id="@+id/nim"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Nim"/>
    <EditText
       android:id="@+id/nama"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Nama Lengkap"/>
    <EditText
       android:id="@+id/tlp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="No Telpon"/>
    <EditText
       android:id="@+id/er_user"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Username"/>
    <EditText
       android:id="@+id/er_pass"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Password"/>
    <Button
       android:id="@+id/btn_regist"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Daftar"/>
    <Button
       android:id="@+id/btn_kembali"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Kembali"/>
</LinearLayout>

DaftarActivity.java
package com.example.perpustakaan;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DaftarActivity extends Activity {
    EditText nim, nama, tlp, user, pass;
    Button daftar, kembali;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daftar);
        nim = (EditText) findViewById(R.id.nim);
        nama = (EditText) findViewById(R.id.nama);
        tlp = (EditText) findViewById(R.id.tlp);
        user = (EditText) findViewById(R.id.er_user);
        pass = (EditText) findViewById(R.id.er_pass);
        daftar = (Button) findViewById(R.id.btn_regist);
        kembali = (Button) findViewById(R.id.btn_kembali);
        daftar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("nim", nama.getText()
                        .toString()));
                postParameters.add(new BasicNameValuePair("nama", nama
                        .getText().toString()));
                postParameters.add(new BasicNameValuePair("tlp", tlp.getText()
                        .toString()));
                postParameters.add(new BasicNameValuePair("username", user
                        .getText().toString()));
                postParameters.add(new BasicNameValuePair("password", pass
                        .getText().toString()));
                String response = null;
                try {
                    response = CustomHttpClient.executeHttpPost(
                            CustomHttpClient.URL + "Registrasi.php",
                            postParameters);
                    String res = response.toString();
                    res = res.trim();
                    res = res.replaceAll("\\s+", "");
                    if (res.equals("1")) {
                        Toast.makeText(getApplicationContext(),
                                "Berhasil Registrasi Akun", Toast.LENGTH_SHORT)
                                .show();
                        Intent intent = new Intent(getApplicationContext(),
                                MainActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Gagal Registrasi Akun", Toast.LENGTH_SHORT)
                                .show();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }}});
        kembali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getApplicationContext(),
                        MainActivity.class);
                startActivity(intent); }
        });}
}

Running dan cek apakah data registrasi berhasil disimpan ke database.

1 komentar:

Copyright © Sharing Pengetahuan | Powered by Blogger