Membuat Crud Client Server

Baiklah Praktikum kali ini kita akan membuat CRUD Client Server.

sebelumnya kita buat database crud_android. buka localhost/phpmyadmin lalu buat database dan tabelnya. nama tabelnya tabel_biodata. lalu akan menjadi seperti gambar dibawah ini :



kemudian buka folder htdocs kita akan membuat sebuah folder dengan nama crud_android didalam crud_android buat sebuah file dengan nama server.php.


setelah kita buat file php nya sekarang kita akan membuat projectnya dengan nama crud_android. berikut gambar dibawah ini :



sekarang kita akan membuat classnya dengan nama biodata.java. berikut ini :

package jhohannes.com;

public class Biodata extends Koneksi {
String URL = "http://10.0.2.2/crud_android/server.php";
String url = "";
String response = "";

public String tampilBiodata() {
try {
url = URL + "?operasi=view";
System.out.println("URL Tampil Biodata: " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String inserBiodata(String nama, String alamat) {
try {
url = URL + "?operasi=insert&nama=" + nama + "&alamat=" + alamat;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String getBiodataById(int id) {
try {
url = URL + "?operasi=get_biodata_by_id&id=" + id;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String updateBiodata(String id, String nama, String alamat) {
try {
url = URL + "?operasi=update&id=" + id + "&nama=" + nama + "&alamat=" + alamat;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

public String deleteBiodata(int id) {
try {
url = URL + "?operasi=delete&id=" + id;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}

}


kemudian kita akan membuat class Koneksi.java. berikut ini :



package jhohannes.com;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Koneksi {

public String call(String url) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(url);
} catch (IOException e) {
e.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// Handle Exception
e.printStackTrace();
return "";
}
return str;
}

private InputStream OpenHttpConnection(String url) throws IOException {
InputStream in = null;
int response = -1;
URL url1 = new URL(url);
URLConnection conn = url1.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not An Http Connection");
try {
HttpURLConnection httpconn = (HttpURLConnection) conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response = httpconn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpconn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting2");
}
return in;
}

}


Setelah itu kita akan membuat class terakhir yaitu class MainActivity. berikut ini :

package jhohannes.com;

import java.util.ArrayList;

import jhohannes.purba.R;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

Biodata biodata = new Biodata();
TableLayout tabelBiodata;

Button buttonTambahBiodata;
ArrayList<Button> buttonEdit = new ArrayList<Button>();
ArrayList<Button> buttonDelete = new ArrayList<Button>();

JSONArray arrayBiodata;

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

tabelBiodata = (TableLayout) findViewById(R.id.tableBiodata);
buttonTambahBiodata = (Button) findViewById(R.id.buttonTambahBiodata);
buttonTambahBiodata.setOnClickListener(this);

TableRow barisTabel = new TableRow(this);
barisTabel.setBackgroundColor(Color.CYAN);

TextView viewHeaderId = new TextView(this);
TextView viewHeaderNama = new TextView(this);
TextView viewHeaderAlamat = new TextView(this);
TextView viewHeaderAction = new TextView(this);

viewHeaderId.setText("ID");
viewHeaderNama.setText("Nama");
viewHeaderAlamat.setText("Alamat");
viewHeaderAction.setText("Action");

viewHeaderId.setPadding(5, 1, 5, 1);
viewHeaderNama.setPadding(5, 1, 5, 1);
viewHeaderAlamat.setPadding(5, 1, 5, 1);
viewHeaderAction.setPadding(5, 1, 5, 1);

barisTabel.addView(viewHeaderId);
barisTabel.addView(viewHeaderNama);
barisTabel.addView(viewHeaderAlamat);
barisTabel.addView(viewHeaderAction);

tabelBiodata.addView(barisTabel, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));

try {

arrayBiodata = new JSONArray(biodata.tampilBiodata());

for (int i = 0; i < arrayBiodata.length(); i++) {
JSONObject jsonChildNode = arrayBiodata.getJSONObject(i);
String name = jsonChildNode.optString("nama");
String alamat = jsonChildNode.optString("Alamat");
String id = jsonChildNode.optString("id");

System.out.println("Nama :" + name);
System.out.println("Alamat :" + alamat);
System.out.println("ID :" + id);

barisTabel = new TableRow(this);

if (i % 2 == 0) {
barisTabel.setBackgroundColor(Color.LTGRAY);
}

TextView viewId = new TextView(this);
viewId.setText(id);
viewId.setPadding(5, 1, 5, 1);
barisTabel.addView(viewId);

TextView viewNama = new TextView(this);
viewNama.setText(name);
viewNama.setPadding(5, 1, 5, 1);
barisTabel.addView(viewNama);

TextView viewAlamat = new TextView(this);
viewAlamat.setText(alamat);
viewAlamat.setPadding(5, 1, 5, 1);
barisTabel.addView(viewAlamat);

buttonEdit.add(i, new Button(this));
buttonEdit.get(i).setId(Integer.parseInt(id));
buttonEdit.get(i).setTag("Edit");
buttonEdit.get(i).setText("Edit");
buttonEdit.get(i).setOnClickListener(this);
barisTabel.addView(buttonEdit.get(i));

buttonDelete.add(i, new Button(this));
buttonDelete.get(i).setId(Integer.parseInt(id));
buttonDelete.get(i).setTag("Delete");
buttonDelete.get(i).setText("Delete");
buttonDelete.get(i).setOnClickListener(this);
barisTabel.addView(buttonDelete.get(i));

tabelBiodata.addView(barisTabel, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

public void onClick(View view) {

if (view.getId() == R.id.buttonTambahBiodata) {
// Toast.makeText(MainActivity.this, "Button Tambah Data",
// Toast.LENGTH_SHORT).show();

tambahBiodata();

} else {
/*
* Melakukan pengecekan pada data array, agar sesuai dengan index
* masing-masing button
*/
for (int i = 0; i < buttonEdit.size(); i++) {

/* jika yang diklik adalah button edit */
if (view.getId() == buttonEdit.get(i).getId() && view.getTag().toString().trim().equals("Edit")) {
// Toast.makeText(MainActivity.this, "Edit : " +
// buttonEdit.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonEdit.get(i).getId();
getDataByID(id);

} /* jika yang diklik adalah button delete */
else if (view.getId() == buttonDelete.get(i).getId() && view.getTag().toString().trim().equals("Delete")) {
// Toast.makeText(MainActivity.this, "Delete : " +
// buttonDelete.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonDelete.get(i).getId();
deleteBiodata(id);

}
}
}
}

public void deleteBiodata(int id) {
biodata.deleteBiodata(id);

/* restart acrtivity */
finish();
startActivity(getIntent());

}

public void getDataByID(int id) {

String namaEdit = null, alamatEdit = null;
JSONArray arrayPersonal;

try {

arrayPersonal = new JSONArray(biodata.getBiodataById(id));

for (int i = 0; i < arrayPersonal.length(); i++) {
JSONObject jsonChildNode = arrayPersonal.getJSONObject(i);
namaEdit = jsonChildNode.optString("nama");
alamatEdit = jsonChildNode.optString("Alamat");
}
} catch (JSONException e) {
e.printStackTrace();
}

LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);

// buat id tersembunyi di alertbuilder
final TextView viewId = new TextView(this);
viewId.setText(String.valueOf(id));
viewId.setTextColor(Color.TRANSPARENT);
layoutInput.addView(viewId);

final EditText editNama = new EditText(this);
editNama.setText(namaEdit);
layoutInput.addView(editNama);

final EditText editAlamat = new EditText(this);
editAlamat.setText(alamatEdit);
layoutInput.addView(editAlamat);

AlertDialog.Builder builderEditBiodata = new AlertDialog.Builder(this);
builderEditBiodata.setIcon(R.drawable.batagrams);
builderEditBiodata.setTitle("Update Biodata");
builderEditBiodata.setView(layoutInput);
builderEditBiodata.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();

System.out.println("Nama : " + nama + " Alamat : " + alamat);

String laporan = biodata.updateBiodata(viewId.getText().toString(), editNama.getText().toString(),
editAlamat.getText().toString());

Toast.makeText(MainActivity.this, laporan, Toast.LENGTH_SHORT).show();

/* restart acrtivity */
finish();
startActivity(getIntent());
}

});

builderEditBiodata.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderEditBiodata.show();

}

public void tambahBiodata() {
/* layout akan ditampilkan pada AlertDialog */
LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);

final EditText editNama = new EditText(this);
editNama.setHint("Nama");
layoutInput.addView(editNama);

final EditText editAlamat = new EditText(this);
editAlamat.setHint("Alamat");
layoutInput.addView(editAlamat);

AlertDialog.Builder builderInsertBiodata = new AlertDialog.Builder(this);
builderInsertBiodata.setIcon(R.drawable.batagrams);
builderInsertBiodata.setTitle("Insert Biodata");
builderInsertBiodata.setView(layoutInput);
builderInsertBiodata.setPositiveButton("Insert", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();

System.out.println("Nama : " + nama + " Alamat : " + alamat);

String laporan = biodata.inserBiodata(nama, alamat);

Toast.makeText(MainActivity.this, laporan, Toast.LENGTH_SHORT).show();

/* restart acrtivity */
finish();
startActivity(getIntent());
}

});

builderInsertBiodata.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderInsertBiodata.show();
}
}


setelah kita membuat classnya sekarang kita membuat layoutnya. main.xml. berikut ini :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/buttonTambahBiodata"
        android:layout_width="186dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Tambah Biodata" />

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ScrollView
            android:id="@+id/verticalScrollView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TableLayout
                android:id="@+id/tableBiodata"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="80dp" >
            </TableLayout>
        </ScrollView>
    </HorizontalScrollView>

</LinearLayout>


setelah kita membuat classnya, sekarang kita akan melihat hasilnya :


 

Membuat Aplikasi Akta

Pada Blog kali ini saya membuat project Akta. dalam project Akta terdiri 5 class dan 4 Layout. sebelum kita membuat project akta, yang pertama kita akan buat yaitu membuat database akta. Nama database : Akta dan terdiri 2 Table yaitu : table daftar_akta dan user.
berikut ini nama-nama class :
  • CostumHttpClient.java
  • Daftar_akta.java
  • Daftar_user.java
  • login.java
  • menulayanan.java
Nama-nama layaout :
  • daftar_akta.xml
  • daftar_user.xml
  • login.xml
  • main.xml
sekarang kita akan membuat class CostumHttpClien.java:

package com.wilis;

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

setelah kita akan membuat class daftar_akta.java :

package com.wilis;

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 daftar_akta extends Activity {
   
   EditText nomor_reg,nama,ttl,jam,anak_ke,ayah_nama,ayah_umur,ayah_pekerjaan,ayah_alamat,ibu_nama,ibu_umur,ibu_pekerjaan,ibu_alamat;
   RadioGroup jk;
   TextView status;
   Button simpan,keluar;
      
    /** Called when the activity is first created. */
    @Override
      
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daftar_akta);
        
        nomor_reg = (EditText)findViewById(R.id.txtnomor_reg);
        nama=(EditText)findViewById(R.id.txtnama);
        ttl=(EditText)findViewById(R.id.txtttl);
        jam=(EditText)findViewById(R.id.txtjam);
        jk=(RadioGroup) findViewById(R.id.jekel);
        anak_ke = (EditText) findViewById (R.id.txtanak_ke);
        ayah_nama = (EditText)findViewById(R.id.txtayah_nama);
        ayah_umur = (EditText)findViewById(R.id.txtayah_umur);
        ayah_pekerjaan = (EditText)findViewById(R.id.txtayah_pekerjaan);
        ayah_alamat = (EditText)findViewById(R.id.txtayah_alamat);
        ibu_nama = (EditText)findViewById(R.id.txtibu_nama);
        ibu_umur = (EditText)findViewById(R.id.txtibu_umur);
        ibu_pekerjaan = (EditText)findViewById(R.id.txtibu_pekerjaan);
        ibu_alamat = (EditText)findViewById(R.id.txtibu_alamat);
                 
        
        simpan=(Button)findViewById(R.id.btnsimpan);
        keluar=(Button)findViewById(R.id.btnexit);
        status=(TextView)findViewById(R.id.txtstatus);
        
        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("nomor_reg", nomor_reg.getText().toString()));
            postParameters.add(new BasicNameValuePair("nama", nama.getText().toString()));
            postParameters.add(new BasicNameValuePair("ttl",ttl.getText().toString()));
            postParameters.add(new BasicNameValuePair("jam",ttl.getText().toString()));
            postParameters.add(new BasicNameValuePair("jekel", type));
            postParameters.add(new BasicNameValuePair("anak_ke", anak_ke.getText().toString()));
            postParameters.add(new BasicNameValuePair("ayah_nama", ayah_nama.getText().toString()));
            postParameters.add(new BasicNameValuePair("ayah_umur", ayah_umur.getText().toString()));
            postParameters.add(new BasicNameValuePair("ayah_pekerjaan", ayah_pekerjaan.getText().toString()));
            postParameters.add(new BasicNameValuePair("ayah_alamat", ayah_alamat.getText().toString()));
            postParameters.add(new BasicNameValuePair("ibu_nama", ibu_nama.getText().toString()));
            postParameters.add(new BasicNameValuePair("ibu_umur", ibu_umur.getText().toString()));
            postParameters.add(new BasicNameValuePair("ibu_pekerjaan", ibu_pekerjaan.getText().toString()));
            postParameters.add(new BasicNameValuePair("ibu_alamat", ibu_alamat.getText().toString()));
            
/*            String valid = "1";*/      
            
            String response = null;
            
            try {
               
               response = CustomHttpClient.executeHttpPost("http://10.0.2.2/akta/daftar_akta.php", postParameters);
               
               String res = response.toString();
               
               res = res.trim();
               
               res = res.replaceAll("\\s+","");
               
               status.setText(res);
               
               if (res.equals("1")) status.setText("Data tidak Tersimpan Ke server");
               
               else status.setText("Data berhasil disimpan ke server");
               
            }
            
            catch (Exception e) {
               
               nomor_reg.setText(e.toString());
               
            }
               
         }
            
            
      });
    }
   
    public void keluar (View theButton)
    {
    Intent a = new Intent (this,menulayanan.class);
    startActivity(a);
    }
}

kemudian kita akan membuat class daftar_user.java :

package com.wilis;

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 daftar_user extends Activity {
   
   EditText ktp,nama,ttl,alamat,agama,pekerjaan,username,password;
   RadioGroup jk;
   TextView status;
   Button simpan;
   
   
    /** Called when the activity is first created. */
   
   @Override
   
   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daftar_user);
       
        
        ktp=(EditText)findViewById(R.id.txtnomorktp);
        nama=(EditText)findViewById(R.id.txtnama);
        ttl=(EditText)findViewById(R.id.txtttl);
        jk=(RadioGroup) findViewById(R.id.jekel);
        alamat=(EditText)findViewById(R.id.txtalamat);
        agama=(EditText)findViewById(R.id.txtagama);
        pekerjaan=(EditText)findViewById(R.id.txtpekerjaan);
        username=(EditText)findViewById(R.id.txtusername);
        password=(EditText)findViewById(R.id.txtpassword);
           
        
        simpan=(Button)findViewById(R.id.btnsimpan);
       // keluar=(Button)findViewById(R.id.btnexit);
        status=(TextView)findViewById(R.id.txtstatus);
        
        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("nomor_ktp", ktp.getText().toString()));
            postParameters.add(new BasicNameValuePair("nama", nama.getText().toString()));
            postParameters.add(new BasicNameValuePair("ttl",ttl.getText().toString()));
            postParameters.add(new BasicNameValuePair("alamat", alamat.getText().toString()));
            postParameters.add(new BasicNameValuePair("jekel", type));
            postParameters.add(new BasicNameValuePair("agama", agama.getText().toString()));
            postParameters.add(new BasicNameValuePair("pekerjaan", pekerjaan.getText().toString()));
            postParameters.add(new BasicNameValuePair("username", username.getText().toString()));
            postParameters.add(new BasicNameValuePair("password", password.getText().toString()));
            
/*            String valid = "1";*/      
            
            String response = null;
            
            try {
               
               response = CustomHttpClient.executeHttpPost("http://10.0.2.2/akta/daftar_user.php", postParameters);
               
               String res = response.toString();
               
               res = res.trim();
               
               res = res.replaceAll("\\s+","");
               
               status.setText(res);
               
               if (res.equals("1")) status.setText("Data tidak Tersimpan Ke server");
               
               else status.setText("Data berhasil disimpan ke server");
               
            }
            
            catch (Exception e) {
               
               username.setText(e.toString());
               
            }
               
         }
            
            
      });
    }
   
    public void keluar (View theButton)
    {
    Intent a = new Intent (this,login.class);
    startActivity(a);
    }
}

setelah membuat class daftar_user, sekarang class login.java :

package com.wilis;

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 {
    /** Called when the activity is first created. */
EditText username,password;
TextView status;
Button login,daftar;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        username=(EditText) findViewById(R.id.txtusername);
        password=(EditText) findViewById(R.id.txtpassword);
        status=(TextView) findViewById (R.id.txtstatus);
        
        login=(Button) findViewById (R.id.btnlogin);
        daftar=(Button) findViewById (R.id.btndaftar);
        
        login.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", username.getText().toString()));
                  
               postParameters.add(new BasicNameValuePair("password", password.getText().toString()));
               
   /*            String valid = "1";*/      
               
               String response = null;
               
               try {
                  
                  response = CustomHttpClient.executeHttpPost("http://10.0.2.2/akta/check.php", postParameters);
                  
                  String res = response.toString();
                  
                  res = res.trim();
                  
                  res = res.replaceAll("\\s+","");
                  
                  status.setText(res);
                  
                  if (res.equals("1")) 
                  {
                  status.setText("Correct Username or Password");
                  berhasil(v); 
                 
                  }
                  else { 
                   status.setText("Sorry!! Wrong Username or Password Entered");
                   
                       }
               }
               
               catch (Exception e) {
                  
                  status.setText(e.toString());
                  
               }
               
            }
            
            });
       
     // penutup buka dari public void onCreate
    }   
        

   
    
    public void daftar (View theButton)
    {
    Intent d = new Intent (this,daftar_user.class);
    startActivity(d);
    }
    

// apabila user berhasil login.
    
    public void berhasil (View theButton)
    {
    Intent s = new Intent (this, menulayanan.class);
    startActivity(s);
    }
    
}

Berikut ini menulayanan :
package com.wilis;


import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class menulayanan extends ListActivity {

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {
super.onCreate(icicle);

// Create an array of Strings, that will be put to our ListActivity
String[] menulayanan = new String[] { "Petunjuk Pendaftaran", "Syarat-syarat pendaftaran", "Form Pendaftaran Kelahiran", "Call Informasi","Exit"};
//Menset nilai array ke dalam list adapater sehingga data pada array akan dimunculkan dalam list
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,menulayanan));
}

@Override
/**method ini akan mengoveride method onListItemClick yang ada pada class List Activity
* method ini akan dipanggil apabilai ada salah satu item dari list menu yang dipilih
*/
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
// Menangkap nilai text yang dklik
Object o = this.getListAdapter().getItem(position);
String pilihan = o.toString();
// Menampilkan hasil pilihan menu dalam bentuk Toast
tampilkanPilihan(pilihan);
}
/**
* Tampilkan Activity sesuai dengan menu yang dipilih
*
*/
protected void tampilkanPilihan(String pilihan) {
try {
//Intent digunakan untuk sebagai pengenal suatu activity
Intent i = null;
if (pilihan.equals("Petunjuk Pendaftaran")) {
i = new Intent(this, login.class);
} else if (pilihan.equals("Syarat-syarat pendaftaran")) {
i = new Intent(this, login.class);
} else if (pilihan.equals("Form Pendaftaran Kelahiran")) {
i = new Intent(this, daftar_akta.class);
} else if (pilihan.equals("Call Informasi")) {
i = new Intent(this, login.class);
} else if (pilihan.equals("Exit")) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure want to Exit?")
.setCancelable(false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent exit = new Intent(
Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
}).show();
} else {
Toast.makeText(this,"Anda Memilih: " + pilihan + " , Actionnya belum dibuat", Toast.LENGTH_LONG).show();
}
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}

setelah kita membuat class sekarang kita akan membuat Layout. Berikut ini kita akan membuat main.xml :

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

kemudian kita akan membuat daftar_akta.xml :


sekarang kita akan membuat daftar_user.xml :


layout login.xml :


setelah kita membuat class dan layaoutnya sekarang kita akan menjalankan projectnya. klik kanan pada project lalu Run As -> Android Application.

hasil running :


Sebelum login, terutama mendaftar kemudian kita bisa login kedalam.











Selesai !!!