Anda di halaman 1dari 21

TUTORIAL MEMBUAT CRUD

Assalamualaikum wr.wb
Tutorial kali ini kita akan membuat crud di android
Alat yang harus di sediakan yaitu :
Android Studio
Dan Jangan Lupa Juga Sebuah Internet.
Sebelum kita melanjutkan kita sediakan dulu sebuah librarynya
Untuk yang lib design dan v4 sesuaikan dengan appcompat kalian
compile
'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.
1.2'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'

tambahkan di androidmanifest.xml
<uses-permission android:name="android.permission.INTERNET" />

buat xml untuk tampilan simpannya .. di sini saya menggunakan activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="supriady.crudmysql.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ednim"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ednama"
android:layout_below="@+id/ednim"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Simpan"
android:background="#900"
android:textColor="#fff"

android:id="@+id/btsimpan"
android:layout_below="@+id/ednama"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Nah selanjutnya kita buat untuk menampilkan data kita dan tombol untuk tambah data .. di sini saya menggunakan
listview dan juga FloatingActionButton

Tampil.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"

android:id="@+id/fab"
android:src="@android:drawable/ic_input_add"
app:layout_anchor="@id/listView"
app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>

Selanjutnya buat custom untuk menampilkan datanya


Beri nama listtampil.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Nim"
android:id="@+id/txtnim" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"

android:text="nama"
android:id="@+id/txtnama" />
</LinearLayout>

Membuat menu untuk pencarian denan cara klik kanan pada res-> directory buat folder dengan nama
menu selanjutnya klik kanan pada folder menu pilih menu resource file beri nama search
Search.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"></item>
</menu>

Setalah itu kita buat database dengan nama dbmahasiswa dan tabal tbmhs

Ok sebelum kita membuat koding untuk CRUD kita buat dulu sebuah jembatan untuk melakukan proses
ke server.. di sini saya menggunakan 2 proses:
1. RequestHandler.java untuk proses simpan
2. JSONParser.java untuk proses tampil

RequestHandler.java
package supriady.polisiprogresif;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class RequestHandler {
public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String result;
StringBuilder sb = new StringBuilder();
while((result = bufferedReader.readLine())!=null){
sb.append(result);
}
return sb.toString();
} catch (Exception e) {
return null;
}

}
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws
UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
JSONParser.java

package supriady.polisiprogresif;
import android.util.Log;
import
import
import
import
import
import
import
import
import
import
import

org.apache.http.HttpEntity;
org.apache.http.HttpResponse;
org.apache.http.NameValuePair;
org.apache.http.client.ClientProtocolException;
org.apache.http.client.entity.UrlEncodedFormEntity;
org.apache.http.client.methods.HttpGet;
org.apache.http.client.methods.HttpPost;
org.apache.http.client.utils.URLEncodedUtils;
org.apache.http.impl.client.DefaultHttpClient;
org.json.JSONException;
org.json.JSONObject;

import
import
import
import
import
import

java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.io.UnsupportedEncodingException;
java.util.List;

public class JSONParser {


static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// Kontraktor
public JSONParser() {
}
// Fungsi pengambil JSON dari URL
// Untuk membuat Method POST dan GET
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Membuat Request HTTP
try {
// Cek Request Metode POST
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new
DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new
UrlEncodedFormEntity(params));
HttpResponse httpResponse =
httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
// Cek Request Metode GET
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new
DefaultHttpClient();
String paramString =
URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;

HttpGet httpGet = new HttpGet(url);


HttpResponse httpResponse =
httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +
e.toString());
}
// mencoba parse String ke JSON Object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +
e.toString());
}
// Mengembalikan Nilai JSON String
return jObj;
}

nah selanjutnya kita buat sebuah koneksi php beri nama folder mhs di htdoc
koneksi.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "dbmahasiswa");
$db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to
Connect');

?>
Setelah itu buat php untuk simpan
Simpan.php
<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$nim=$_POST['nim'];
$nama=$_POST['nama'];
$simpan = "insert into tbmhs(nim,nama) values('$nim','$nama')";
if
(mysqli_query($db,$simpan)){
echo "sukses";
}else{
echo "Gagal";
}
}
?>
Selanjutnya buat tampilmhs.php
<?php
include'koneksi.php';
$response = array();
$response["Hasil"] = array();
$result = mysqli_query($db,"SELECT * FROM tbmhs") or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
$response["Hasil"] = array();
while($row = mysqli_fetch_array($result)){
$hasil = array();
$hasil["nim"] = $row["nim"];
$hasil["nama"] = $row["nama"];
array_push($response["Hasil"],$hasil);
$response["success"] = 1;
}
echo json_encode($response);
}else{
$response["success"] = 0;
echo json_encode($response);
}
?>
Hapus.php
<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST'){

$nim=$_POST['nim'];
$edit = "delete from tbmhs where nim='$nim'";
if

(mysqli_query($db,$edit)){
echo "sukses";

}else{
echo "Gagal";
}
}

?>

carimhs.php
<?php
include'koneksi.php';
$response = array();
$response["Hasil"] = array();
$nim = $_GET['nim'];
$result = mysqli_query($db,"SELECT * FROM tbmhs where nim='$nim'") or die(mysqli_error());
if (mysqli_num_rows($result) > 0){
$response["Hasil"] = array();
while($row = mysqli_fetch_array($result)){
$hasil = array();
$hasil["nim"] = $row["nim"];
$hasil["nama"] = $row["nama"];
array_push($response["Hasil"],$hasil);
$response["success"] = 1;

}
echo json_encode($response);

}else{
$response["success"] = 0;
echo json_encode($response);
}
?>
Update.php
<?php
require_once('koneksi.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$nim=$_POST['nim'];
$nama=$_POST['nama'];
$edit = "update tbmhs set nama='$nama' where nim='$nim'";
if

(mysqli_query($db,$edit)){
echo "sukses";

}else{
echo "Gagal";
}
}

?>

Setelah kita selesai membuat file phpnya selanjutnya kita buat untuk proses di androidnya
Untuk proses simpan di sini saya meletakkan kodenya di MainActivity.java pada proses ini kita tidak
memerlukan library , dan proses untuk jembatan pengantar ke server menggunakan RequestHandler.java

package supriady.crudmysql;
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.os.AsyncTask;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
String _nim,_nama;
EditText ednim,ednama;
Button btsimpan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ednim = (EditText)findViewById(R.id.ednim);
ednama = (EditText)findViewById(R.id.ednama);
btsimpan = (Button)findViewById(R.id.btsimpan);
btsimpan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_nim = ednim.getText().toString();
_nama = ednama.getText().toString();
simpanServer();
}
});
}
private void simpanServer() {
class simpanServer extends AsyncTask<String, String,String> {
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Simpan");
pd.show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG)
.show();
pd.dismiss();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("nim", _nim);
data.put("nama", _nama);
rh.sendPostRequest("http://10.0.2.2/mhs/simpan.php", data);
return null;

}
}
simpanServer ui = new simpanServer();
ui.execute();
}
}

nah silahkan di jalankan aplikasinya


selanjutnya kita akan buat proses menampilkan data menggunakan custom
proses ini memerlukan library yg telah kita download tadi compile
'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.
1.2'

di dalam file ini sudah tersedia pencarian, opsi edit,hapus


tampilmhs.php
package supriady.crudmysql;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.app.SearchManager;
android.content.DialogInterface;
android.content.Intent;
android.os.AsyncTask;
android.os.Bundle;
android.support.design.widget.FloatingActionButton;
android.support.v4.content.ContextCompat;
android.support.v4.view.MenuItemCompat;
android.support.v7.app.AlertDialog;
android.support.v7.app.AppCompatActivity;
android.support.v7.widget.SearchView;
android.view.MenuItem;
android.view.View;
android.widget.AdapterView;
android.widget.EditText;
android.widget.ListView;
android.widget.Toast;

import
import
import
import
import

org.apache.http.NameValuePair;
org.apache.http.message.BasicNameValuePair;
org.json.JSONArray;
org.json.JSONException;
org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by GOBLIN on 8/16/2016.
*/
public class tampilmhs extends AppCompatActivity {
String url_tampil = "http://10.0.2.2/mhs/tampilmhs.php";
String url_cari = "http://10.0.2.2/mhs/carimhs.php";
ListView liv;
HashMap<String, String> map;
ProgressDialog progressDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> tampil = new ArrayList<HashMap<String,
String>>();
public static String TAGnim = "nim";
public static String TAGnama = "nama";

String nim,nama;
JSONArray string_json = null;
custommhs adapter;
int posisi;
private ProgressDialog pd;
//opsi pilihan
String[] daftaropsi = {"Edit","Hapus"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tampil);
liv = (ListView) findViewById(R.id.listView);
//menampilkan data
new ambiltampil().execute();
//inisialisasi FloatingActionButton
FloatingActionButton tbtambah = (FloatingActionButton)findViewById(R.id.fab);
tbtambah.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(tampilmhs.this,MainActivity.class));
}
});
//Proses ketika list di tekan lama
liv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int
position, long id) {
//mengambil posisi list yg di klik
posisi=position;
//menampilkan opsi pilihan edit, hapus
AlertDialog.Builder kotakDialog = new AlertDialog.Builder(
tampilmhs.this);
kotakDialog.setCancelable(true);
kotakDialog.setTitle("Opsi");
//membuat event klik pada opsi pilihan
kotakDialog.setItems(daftaropsi, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id1) {
//ketika memilih opsi index ke 0 atau opsi edit
if(id1==0){
//mengambil data pada item yg di klik
HashMap<String, String> map = tampil.get(posisi);
nim = String.valueOf(map.get(TAGnim));
nama = String.valueOf(map.get(TAGnama));
//membuat intent untuk melakukan proses edit dan membawa
data pada item list yang di klik tadi
Intent intent = new Intent(tampilmhs.this,edit.class);
intent.putExtra("nim",nim.toString());
intent.putExtra("nama",nama.toString());
startActivity(intent);
}
//ketika memilih opsi index ke 1 atau opsi hapus
if (id1 == 1) {
//mengambil data pada item yg di klik
HashMap<String, String> map = tampil.get(posisi);
nim = String.valueOf(map.get(TAGnim));
hapus();
//ketika proses hapus berhasil menampilkan data yg baru
new ambiltampil().execute();
}
}

});
kotakDialog.create().show();
return true;
}
});
}
//menampilkan data yang di kirim dari custom
public void SetListViewAdapter(ArrayList<HashMap<String, String>> berita) {
adapter = new custommhs(tampilmhs.this, berita);
liv.setAdapter(adapter);
}
//proses ambil data dari server
class ambiltampil extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(tampilmhs.this);
progressDialog.setMessage("Mohon Tungu...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(url_tampil, "POST", params);
try {
string_json = json.getJSONArray("Hasil");
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tampil.clear();
for (int i = 0; i < string_json.length(); i++) {
JSONObject object = string_json.getJSONObject(i);
// Menampung hasil Object pada Variabel
map = new HashMap<String, String>();
map.put(TAGnim, object.getString(TAGnim));
map.put(TAGnama, object.getString(TAGnama));
tampil.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (
JSONException e
)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
progressDialog.dismiss();

runOnUiThread(new Runnable() {
@Override
public void run() {
SetListViewAdapter(tampil);
}
});
}
}
//proses membuat menu pencarian
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.search,menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
if(searchItem !=null){
SearchView searchView = (SearchView)
MenuItemCompat.getActionView(searchItem);
searchView.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
return false;
}
});
EditText searchplate =
(EditText)searchView.findViewById(R.id.search_src_text);
searchplate.setHint("Ketikkan Nim");
View searchview = searchView.findViewById(R.id.search_plate);
searchview.setBackgroundColor(ContextCompat.getColor(this,
android.R.color.transparent));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//query adalh data yang telah kita ketik
nim= query.toString();
new cari().execute();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
SearchManager searchManager =
(SearchManager)getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
//proses pencarian
class cari extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(tampilmhs.this);
progressDialog.setMessage("Mohon Tungu...");
progressDialog.setIndeterminate(false);

progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nim",nim.toString()));
JSONObject json = jsonParser.makeHttpRequest(url_cari, "GET", params);
try {
string_json = json.getJSONArray("Hasil");
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tampil.clear();
for (int i = 0; i < string_json.length(); i++) {
JSONObject object = string_json.getJSONObject(i);
// Menampung hasil Object pada Variabel
map = new HashMap<String, String>();
map.put(TAGnim, object.getString(TAGnim));
map.put(TAGnama, object.getString(TAGnama));
tampil.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (
JSONException e
)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
SetListViewAdapter(tampil);
}
});
}
}
//proses hapus
private void hapus() {
class hapus extends AsyncTask<String, String,String> {
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(tampilmhs.this);
pd.setMessage("Edit");
pd.show();

}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG)
.show();
pd.dismiss();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("nim", nim);
rh.sendPostRequest("http://10.0.2.2/mhs/hapus.php", data);
return null;
}
}
hapus ui = new hapus();
ui.execute();
}
}

nah selanjutnya kita buat file custommhs.java


package supriady.crudmysql;
import
import
import
import
import
import
import

android.app.Activity;
android.content.Context;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.BaseAdapter;
android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by GOBLIN on 6/21/2016.
*/
public class custommhs extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String,String>> data;
HashMap<String,String> data_tampil = new HashMap<String,String>();
private static LayoutInflater inflater = null;
//StreamFragmentManager
public custommhs(Activity a, ArrayList<HashMap<String, String>> d){
activity=a;
data=d;
inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override

public Object getItem(int position) {


return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi =convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.littampil,null);
TextView nim = (TextView)vi.findViewById(R.id.txtnim);
TextView nama = (TextView)vi.findViewById(R.id.txtnama);
data_tampil = data.get(position);
nim.setText(data_tampil.get(tampilmhs.TAGnim));
nama.setText(data_tampil.get(tampilmhs.TAGnama));
return vi;
}
}

setelah itu buat file edit.java


package supriady.crudmysql;
import
import
import
import
import
import
import
import
import

android.app.ProgressDialog;
android.content.Intent;
android.os.AsyncTask;
android.os.Bundle;
android.support.v7.app.AppCompatActivity;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

import java.util.HashMap;
public class edit extends AppCompatActivity {
private ProgressDialog pd;
String _nim,_nama;
EditText ednim,ednama;
Button btsimpan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ednim = (EditText)findViewById(R.id.ednim);
ednama = (EditText)findViewById(R.id.ednama);
Intent intent = getIntent();
_nim = intent.getStringExtra("nim");
_nama = intent.getStringExtra("nama");
ednim.setText(_nim);
ednama.setText(_nama);
btsimpan = (Button)findViewById(R.id.btsimpan);
btsimpan.setText("EDIT");
btsimpan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_nim = ednim.getText().toString();

_nama = ednama.getText().toString();
Edit();
}
});
}
private void Edit() {
class Edit extends AsyncTask<String, String,String> {
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(edit.this);
pd.setMessage("Edit");
pd.show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG)
.show();
pd.dismiss();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("nim", _nim);
data.put("nama", _nama);
rh.sendPostRequest("http://10.0.2.2/mhs/update.php", data);
return null;
}
}
Edit ui = new Edit();
ui.execute();
}
}

edit androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="supriady.crudmysql">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".tampilmhs">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"></activity>

<activity android:name=".edit"></activity>
</application>
</manifest>