Tags

,

Hubungi penulis di email : uxc.wilis@gmail.com

CONTOH KASUS i.

Aplikasi client server database

android sebagai client akan berhubungan dengan mysql server dengan perantara php, secara konsep dasar di gambarkan sebagai berikut :

Dalam kasus ini kita akan membuat sebuah form isian data user yang berfungsi untuk menginputkan data dari android ke mysql server.

siapkan terlebih dahulu database serta tabel mysql nya

membuat databasenya

create database latihan

membuat tabel user

create table user
{
username varchar(20) NOT NULL,
password varchar(20) NOT NULL,
repassword varchar(20) NOT NULL,
nama_lengkap varchar(40) NOT NULL,
jekel varchar(10) NOT NULL,
alamat varchar(30) NOT NULL,
nomor_tlp varchar(10) NOT NULL,
nomor_hp varchar(12) NOT NULL,
PRIMARY KEY (`username`)
)

Dalam latihan ini akan digunakan php sebagai web service (controller).

simpan.php

 <?php
    $un=$_POST['username'];
    $pw=$_POST['password'];
    $rpw=$_POST['repassword'];
    $nl=$_POST['nama'];
    $jk=$_POST['jekel'];
    $al=$_POST['alamat'];
    $nt=$_POST['nomor_tlp'];
    $nh=$_POST['nomor_hp'];

	

    $conn = mysql_connect("localhost","root","");
    mysql_select_db("latihan");



$query = "INSERT INTO user (username,password,repassword,nama_lengkap,jekel,alamat,nomor_tlp,nomor_hp) values ('$un','$pw','$rpw','$nl','$jk','$al','$nt','$nh')";
$result = mysql_query($query) or die("REPORTGagal Query Simpan DATA.");
 
   
?>

penggunaan _POST atau tanpa _POST tergantung setting variable globals sistem apache/php yang anda gunakan, apa on/off.

Persiapkan layout tampilan program android seperti gambar berikut :

tambah_user.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff00ffff"
    >
    
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:text="Silakan Masukkan Data Pengguna"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000ff"
/>

<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Username:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:id="@+id/et_un" 
android:maxWidth="140sp"
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>

<TableRow>
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>

<EditText android:id="@+id/et_pw" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>


<TableRow>
<TextView
android:text="retype-Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:layout_height="wrap_content" 
android:id="@+id/et_rpw" 
android:layout_width="match_parent"
android:inputType="textPassword">
</EditText>
</TableRow>



<TableRow>
<TextView
android:text="Nama Lengkap:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:layout_height="wrap_content" 
android:id="@+id/et_nama" 
android:layout_width="match_parent">
</EditText>
</TableRow>

<TableRow>
<TextView android:text="Jekel:" 
          android:textColor="#ff0000ff"/>
          
<RadioGroup android:id="@+id/jekel">
<RadioButton android:id="@+id/pria"
             android:text="Pria"
/>
<RadioButton android:id="@+id/perempuan"
             android:text="Perempuan"
/>
</RadioGroup>
</TableRow>


<TableRow>
<TextView
android:text="Alamat:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:layout_height="wrap_content" 
android:id="@+id/et_alamat" 
android:layout_width="match_parent">
</EditText>
</TableRow>

<TableRow>
<TextView
android:text="Nomor Tlp:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:layout_height="wrap_content" 
android:id="@+id/et_notel" 
android:layout_width="match_parent">
</EditText>
</TableRow>

<TableRow>
<TextView
android:text="Nomor HP:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>


<EditText android:layout_height="wrap_content" 
android:id="@+id/et_nohp" 
android:layout_width="match_parent">
</EditText>
</TableRow>


<TableRow >
<Button android:text="S I M P A N" 
android:id="@+id/btn_simpan" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>

<Button android:text="K E L U A R" 
android:id="@+id/btn_keluar" 
android:onClick="keluar"
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>

</TableRow>

<TextView
android:text=""
android:id="@+id/error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>

</TableLayout>
</ScrollView>

tambah_user.java

package com.wilis.entrydatamysql;

import java.util.ArrayList;

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

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

public class tambah_user extends Activity {
   
   EditText un,pw,rpw,nl,al,nt,nh;
   RadioGroup jk;
   TextView error;
   Button simpan,keluar;
   
   
    /** Called when the activity is first created. */
   
   @Override
   
   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tambah_user);
       
        un=(EditText)findViewById(R.id.et_un);
        pw=(EditText)findViewById(R.id.et_pw);
        rpw=(EditText)findViewById(R.id.et_rpw);
        nl=(EditText) findViewById(R.id.et_nama);
        jk=(RadioGroup) findViewById(R.id.jekel);
        al=(EditText) findViewById(R.id.et_alamat);
        nt=(EditText) findViewById(R.id.et_notel);
        nh=(EditText) findViewById(R.id.et_nohp);
        
        
        simpan=(Button)findViewById(R.id.btn_simpan);
        keluar=(Button)findViewById(R.id.btn_keluar);
        error=(TextView)findViewById(R.id.error);
        simpan.setOnClickListener(new View.OnClickListener() {
         
         @Override
         
         public void onClick(View v) {
            
            // TODO Auto-generated method stub
        	 
        	//atur variabel utk menampung pilihan jenis kelamin
        	 String type=null;
        	 switch (jk.getCheckedRadioButtonId()) {
        	 case R.id.pria:
        	 type="Pria";
        	 break;
        	 case R.id.perempuan:
        	 type="Perempuan";
        	 break;
        	 }
        	     	 
            
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
            postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
            postParameters.add(new BasicNameValuePair("repassword", rpw.getText().toString()));
            postParameters.add(new BasicNameValuePair("nama", nl.getText().toString()));
            postParameters.add(new BasicNameValuePair("jekel", type));
            postParameters.add(new BasicNameValuePair("alamat", al.getText().toString()));
            postParameters.add(new BasicNameValuePair("nomor_tlp", nt.getText().toString()));
            postParameters.add(new BasicNameValuePair("nomor_hp", nh.getText().toString()));
            
/*            String valid = "1";*/      
            
            String response = null;
            
            try {
               
               response = CustomHttpClient.executeHttpPost("http://10.0.2.2/hellomysql/simpan.php", postParameters);
               
               String res = response.toString();
               
               res = res.trim();
               
               res = res.replaceAll("\\s+","");
               
               error.setText(res);
               
                              
            }
            
            catch (Exception e) {
               
               un.setText(e.toString());
               
            }
               
         }
            
            
      });
    }
   
    public void keluar (View theButton)
    {
    	Intent a = new Intent (this,login.class);
    	startActivity(a);
    }
}


Penggunaan 10.0.2.2 adalah untuk identifikasi server localhost.

CustomHttpClient.java

package com.wilis.entrydatamysql;

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 {
   /** 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();
                }
            }
        }
    }
}



Jalankan project dan lakukan input data di form android seperti contoh berikut :

pastikan data sudah tersimpan didalam mysql server

Next : Form Master Entry Data ke Mysql dengan tehnik parse dgn Json dan ksoap2