BELAJAR ANDROID FORM LOGIN PART 02

Login Client Server


Sebuah aplikasi sudah wajib dengan adanya form Login, karena login adalah form untuk hak akases si user untuk masuk ke dalam suatu aplikasi. kali ini saya akan Post untuk form Login android client server, di akhir tutorial saya sertakan juga project utuk dapat di download. 
Sebelumnya saya akan menjelaskan bagaimana sih prosesnya?
1.  android akan mengirimkan data ke PHP.
2.  PHP akan menerima dan menjalan konsisi yang telah di tentukan (mencocokan) ke server.
3.  PHP akan memberikan respon dan android menerima respon tersebut.



lebih seperti itu

dah cukup ya basa-basinya... sekarang gimana sich bikinnya??? saya sudah asumsikan semua sudah ada program aclipse untuk pembuatannya, karena saya menggunakan IDE Eclipse Indigo untuk pembuatan ini:

buat database dengan nama "coba" nama tabel "user" contohnya seperti ini: 


klo sudah bikin database sekarang file login.php login.php <?php 
 $un = $_POST['username'];
 $pw = $_POST['password'];
 $conn = mysql_connect("localhost","root","");    mysql_select_db("coba");
 $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;
 } 
 ?>
Setelah Persiapan dengan database dan file login.php jangan lupa pada htdoct buat folder dengan nama "coba" simpan file login.php pada folder coba! dan coba jalankan pada browser masing-masing "localhost/coba/login.php jika hasilnya adalah "0" berarti sudah berhasil/sukses.

lupakan sejenak untuk database dan file login.php!
Sekrang Membuat Project android di eclipse dengan nama ProjectLogin, contohnya bisa diliat dibawah ini.


menentukan nama Projectnya, lalu pilih Target SDKnya, disini saya menggunakan Android 2.3.3


setelah dipilih targetnya tentukan nama aplikasi, pakage, aktivity dan minimun SDK,yang akan tampil nanti pada aplikasi yang akan di buat!
  
sekarang sudah jadi untuk project yang akan kita buat dengan nama ProjectLogin, nama aplikasinya Login. pada clas Login isikan coding seperti di bawah ini:


login.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/relativeLayout2"     android:layout_width="wrap_content"     android:layout_height="wrap_content" >
    <LinearLayout         android:id="@+id/linearlayout0"         android:layout_width="fill_parent"         android:layout_height="match_parent"         android:layout_alignParentLeft="true">
        <TextView             android:id="@+id/txt1"             android:layout_width="fill_parent"             android:layout_height="wrap_content"             android:layout_marginTop="10dp"             android:textSize="25dp" />     
 </LinearLayout>
 <LinearLayout      android:id="@+id/linearlayout11"      android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:layout_alignParentLeft="true"       android:layout_marginTop="50dp"      android:layout_marginLeft="37dp">
     <TextView
         android:id="@+id/textview11"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="Username "/> 
 </LinearLayout> 

 <LinearLayout      android:id="@+id/linearlayout12"   android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:layout_alignParentLeft="true"      android:layout_below="@+id/linearlayout11"      android:gravity="center" >      <EditText          android:id="@+id/txtuser"          android:layout_width="250dp"          android:layout_height="wrap_content" />
 </LinearLayout>
 <LinearLayout      android:id="@+id/linearlayout13"      android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:layout_below="@+id/linearlayout12"      android:layout_alignParentLeft="true"      android:layout_marginLeft="37dp">
     <TextView          android:id="@+id/textview12"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="Password "/>
 </LinearLayout>
 <LinearLayout      android:id="@+id/linearlayout14"      android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:layout_below="@+id/linearlayout13"      android:layout_alignParentLeft="true"   android:gravity="center">      <EditText  android:id="@+id/txtpassword"  android:layout_width="250dp"  android:layout_height="wrap_content"             android:inputType="textPassword"/>
 </LinearLayout>

 <LinearLayout      android:id="@+id/linearlayout15"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_alignParentLeft="true"      android:layout_below="@+id/linearlayout14"      android:layout_marginLeft="180dp"      android:layout_marginTop="5dp" >
     <Button       android:id="@+id/btnlogin"       android:layout_width="102dp"       android:layout_height="wrap_content"       android:layout_alignParentRight="true"       android:layout_below="@+id/linearlayout14"       android:text="Login"/>
 </LinearLayout>
</RelativeLayout>



menu.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">
    <LinearLayout     android:id="@+id/LinearLayout01"     android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
    android:layout_marginTop="70dp"
        android:orientation="vertical" >
        <TextView             android:id="@+id/tmenuutama"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_gravity="center"             android:text="MENU UTAMA" />
    </LinearLayout>

    <LinearLayout         android:id="@+id/LinearLayout02"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_alignParentTop="true"         android:layout_marginTop="120dp"          android:layout_marginLeft="120dp">
        <ImageButton             android:id="@+id/btn_logout"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:src="@drawable/ic_launcher"             android:onClick="allclickhandler"/>
    </LinearLayout>

    <LinearLayout         android:id="@+id/LinearLayout03"         android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="120dp"  android:layout_marginLeft="160dp">
</LinearLayout>
    
    <LinearLayout         android:id="@+id/LinearLayout04"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_alignParentTop="true"          android:layout_marginTop="215dp"          android:layout_marginLeft="65dp">
    </LinearLayout>

    <LinearLayout         android:id="@+id/LinearLayout05"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_alignParentTop="true"          android:layout_marginTop="215dp"          android:layout_marginLeft="160dp">
    </LinearLayout>
    
</RelativeLayout>


Login.java package com.login.tes; 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 login;
   String i;   
   @Override         public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.login);                 un=(EditText)findViewById(R.id.txtuser);                 pw=(EditText)findViewById(R.id.txtpassword);                 login=(Button)findViewById(R.id.btnlogin);                 error=(TextView)findViewById(R.id.txt1);                 login.setOnClickListener(new View.OnClickListener() 
        {
         public void onClick(View v) {                  
            ArrayList<NameValuePair> postParameters = new
ArrayList<NameValuePair>();             
            postParameters.add(new BasicNameValuePair("username", un.getText().toString()));                             postParamete rs.add(new BasicNameValuePair("password", pw.getText().toString()));                                    String response = null;                          try { 
             response = CustomHttpClient.executeHttpPost("http://10.0.2.2/coba/login.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");                 gagal_login(v);                   //un.setText("");
                //pw.setText("");
               }             }             catch (Exception e) {                                un.setText(e.toString());                
            }     finish();           
         }            
      });
   }    
   
//=========================================================
   public void berhasil_login (View theButton)
    {
        Intent s = new Intent (this, Menu.class);         startActivity(s);
    }
//=========================================================
    public void gagal_login (View theButton)
    {
       Intent s = new Intent (this, Login.class);        s.putExtra("status", "baru");        startActivity(s);
   }    
}

Menu.java  package com.login.tes;

import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast;

public class Menu extends Activity{   public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);                 //Memanggil layout yang pertama sekali ditampilkan         setContentView(R.layout.menu);
        } 
 // Bagian ini untuk handler button pada widget     public void allclickhandler(View view) {
     Intent i = null;        switch (view.getId()) {     case R.id.btn_logout: 
       Toast.makeText(getApplicationContext(), "LOGOUT",50).show();        i = new Intent(this, Login.class);        i.putExtra("status", "baru");     startActivity(i);     break;         }   finish();
    }
}


CustomHttpClien.java package com.login.tes;  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();
               }
           }
   }
} }

Yang terakhir biasa dilupakan adalah manifest AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.login.tes"     android:versionCode="1"     android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name" >
        <activity             android:label="@string/app_name"             android:name=".Login" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>    
        <activity android:name=".CustomHttpClient" ></activity>
        <activity android:name=".Menu" ></activity>       
    </application>
</manifest>



selesai bgitulah login clinetsrver yang saya bisah buat 

Komentar