Tags

, ,

Sumber : Buku on Progressing (contoh kasus conection dgn apache.http.client.HttpClient teknik I)

Penulis Juga menerima dan mengerjakan project-project aplikasi client-server database (aplikasi transaksi,input,laporan,dll) berbasis android, baik itu menggunakan database mysql server, oracle, dll. bisa bertindak sebagai programmer maupun konsultan pembangunan aplikasinya.

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

Aplikasi client server database

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

Dianjurkan sudah baca postingan Form master android postingan sebelumnya.


Contoh teknik dasar formlogin di android.

Buatlah project android baru
Project Name : Formlogin
Buitl Target : Android 2.2
Application name : login
Package name : com.wilis.formlogin
Activity : login
Min SDK : 8

Rancanglah tampilan formlogin kita, mungkin bisa seperti contoh berikut :

dari gambar tsb didapatkan coding xml kita adalah sebagai berikut :

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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 Login sebelum memakai aplikasi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>

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


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

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


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

<TableRow >
<Button android:text="Login" 
android:id="@+id/btn_login" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>

<Button android:text="Cancel" 
android:id="@+id/btn_cancel" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>

</TableRow>


<TextView android:text="" 
android:layout_height="wrap_content" 
android:id="@+id/tv_error" 
android:layout_width="wrap_content">
</TextView>

<TextView android:text="" 
android:layout_height="wrap_content" 
android:id="@+id/ljarak1" 
android:layout_width="wrap_content">
</TextView>

<TextView android:text="Belum Memiliki Account" 
android:layout_height="wrap_content" 
android:id="@+id/ljarak2" 
android:layout_width="wrap_content"
android:textColor="#ff0000ff">
</TextView>

<Button android:text="Buat Account" 
android:layout_height="wrap_content" 
android:id="@+id/daftar" 
android:onClick="tambah_user"
android:layout_width="wrap_content">
</Button>
</TableLayout>
</LinearLayout>

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`)
)

dianjurkan untuk langsung melakukan pengisian data user supaya nanti ada data yang akan kita gunakan login di aplikasi.

Siapkan file php untuk penghubung ke database dan seleksi user yang dikrim dari file java ntar.

check.php

    <?php

    $un=$_POST['username'];
    $pw=$_POST['password'];

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

    $query = "SELECT * FROM user WHERE username = '$un' AND password ='$pw'";
    $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

    
   if (mysql_num_rows($result) == 1){
   
	    echo 1;
	}
   else {
 
	    // print status message
   	   echo 0;
	}

    ?>

berikut adalah coding javanya..

login.java

package com.wilis.formlogin;

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.TextView;

public class login extends Activity {
   
   EditText un,pw;
   TextView error;
   Button simpan,cancel,daftar;
   String i;
   
   
    /** Called when the activity is first created. */
   
   @Override
   
   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        un=(EditText)findViewById(R.id.et_un);
       
        pw=(EditText)findViewById(R.id.et_pw);
       
        simpan=(Button)findViewById(R.id.btn_login);
       
        error=(TextView)findViewById(R.id.tv_error);
       
        simpan.setOnClickListener(new View.OnClickListener() {
         
         @Override
         
         public void onClick(View v) {
            
            // TODO Auto-generated method stub
            
            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            
            postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
               
            postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
            
/*            String valid = "1";*/      
            
            String response = null;
            
            try {
               
               response = CustomHttpClient.executeHttpPost("http://10.0.2.2/hellomysql/check.php", postParameters);
               
               String res = response.toString();
               
               res = res.trim();
               
               res = res.replaceAll("\\s+","");
               
               error.setText(res);
               
               if (res.equals("1")) 
               {
            	   error.setText("Username dan Password benar");
            	   berhasil_login(v);
            	   
            	              	   
               }
               else { 
            	    error.setText("Sorry!! Username or Password salah");
            	    
                    }
            }
            
            catch (Exception e) {
               
               un.setText(e.toString());
               
            }
               
         }
            
            
      });
   }
   
    public void tambah_user (View theButton)
    {
    	Intent i = new Intent(this,tambah_user.class);
    	startActivity(i);
    }
    
    public void berhasil_login (View theButton)
    {
    	Intent s = new Intent (this, menu_utama.class);
    	startActivity(s);
    }
}


CustomHttpClient.java

package com.wilis.formloginmysql;

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


Next : Aplikasi login dengan tehnik parse json dan ksoap2