Anda di halaman 1dari 22

Membuat Aplikasi Android CRUD

Menggunakan Database MySQL


Dedy Kuncoro1 year ago0 comments

MySQL adalah sebuah perangkat lunak sistem manajemen basis data SQL, atau DBMS yang
multithread dan multi-user. MySQL adalah Relational Database Management System
(RDBMS) yang berada dibawah lisensi GPL (General Public License). MySQL, sebenarnya
merupakan turunan dari SQL. SQL (Structured Query Language) adalah sebuah konsep
pengoperasian database, terutama untuk pemilihan atau seleksi dan pemasukan data, yang
memungkinkan pengoperasian data dikerjakan dengan mudah secara otomatis.

CRUD (Create Read Update Delete) adalah sebuah sebuatan untuk aplikasi dimana pengguna
dapat menambah, mengedit dan menghapus data. Aplkasi ini menggunakan floating action
button untuk memanggil form biodata untuk menambah atau mengedit data. Semua data akan
ditampilkan pada listview. Untuk mengedit atau menghapus data pengguna harus menekan
lama salah satu data pada listview untuk menampilkan action edit atau delete.

Langsung saja pertama membuat database dengan nama kuncoro_crud dengan nama tabel
biodata dan struktur tabelnya seperti berikut :

Column name Data Type lenght Primary Key Not Null Auto Increment
id int 10 v v v
nama varchar 50
alamat varchar 100

Membuat web service untuk parsing data aplikasi android.


koneksi.php
Sebagai koneksi aplikasi ke database. Coding-nya disini.

<?php

$server = "localhost"; // sesuaikan alamat server anda


$user = "root"; // sesuaikan user web server anda
$password = "enter"; // sesuaikan password web server anda
$database = "kuncoro_crud"; // sesuaikan database web server
anda

$connect = mysql_connect($server, $user, $password) or die


("Koneksi gagal!");
mysql_select_db($database) or die ("Database belum siap!");
?>
select.php
Untuk menampilkan semua data biodata. Coding-nya disini.

<?php
include "koneksi.php";

$query = mysql_query("SELECT * FROM biodata ORDER BY nama ASC");

$json = array();

while($row = mysql_fetch_assoc($query)){
$json[] = $row;
}

echo json_encode($json);

mysql_close($connect);

?>

insert.php
Untuk menambah data biodata ke database. Coding-nya disini.

<?php
include "koneksi.php";

$nama = $_POST['nama'];
$alamat = $_POST['alamat'];

class emp{}

if (empty($nama) || empty($alamat)) {
$response = new emp();
$response->success = 0;
$response->message = "Kolom isian tidak boleh kosong";
die(json_encode($response));
} else {
$query = mysql_query("INSERT INTO biodata (id,nama,alamat)
VALUES(0,'".$nama."','".$alamat."')");

if ($query) {
$response = new emp();
$response->success = 1;
$response->message = "Data berhasil di simpan";
die(json_encode($response));
} else{
$response = new emp();
$response->success = 0;
$response->message = "Error simpan Data";
die(json_encode($response));
}
}
?>
edit.php
Untuk mengambil salah satu data biodata dari database sebagai parameter meng-update.
Coding-nya disini.

<?php
include "koneksi.php";

$id = $_POST['id'];

class emp{}

if (empty($id)) {
$response = new emp();
$response->success = 0;
$response->message = "Error Mengambil Data";
die(json_encode($response));
} else {
$query = mysql_query("SELECT * FROM biodata WHERE id='".
$id."'");
$row = mysql_fetch_array($query);

if (!empty($row)) {
$response = new emp();
$response->success = 1;
$response->id = $row["id"];
$response->nama = $row["nama"];
$response->alamat = $row["alamat"];
die(json_encode($response));
} else{
$response = new emp();
$response->success = 0;
$response->message = "Error Mengambil Data";
die(json_encode($response));
}
}
?>

update.php
Untuk meng-update data biodata. Coding-nya disini.

<?php
include "koneksi.php";

$id = $_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];

class emp{}

if (empty($id) || empty($nama) || empty($alamat)) {


$response = new emp();
$response->success = 0;
$response->message = "Kolom isian tidak boleh kosong";
die(json_encode($response));
} else {
$query = mysql_query("UPDATE biodata SET nama='".$nama."',
alamat='".$alamat."' WHERE id='".$id."'");
if ($query) {
$response = new emp();
$response->success = 1;
$response->message = "Data berhasil di update";
die(json_encode($response));
} else{
$response = new emp();
$response->success = 0;
$response->message = "Error update Data";
die(json_encode($response));
}
}
?>

delete.php
Untuk menghapus data biodata. Coding-nya disini.

<?php
include "koneksi.php";

$id = $_POST['id'];

class emp{}

if (empty($id)) {
$response = new emp();
$response->success = 0;
$response->message = "Error hapus Data";
die(json_encode($response));
} else {
$query = mysql_query("DELETE FROM biodata WHERE id='".
$id."'");

if ($query) {
$response = new emp();
$response->success = 1;
$response->message = "Data berhasil di hapus";
die(json_encode($response));
} else{
$response = new emp();
$response->success = 0;
$response->message = "Error hapus Data";
die(json_encode($response));
}
}
?>
Buat project baru di Android Studio File New Project. Kemudian pilih Blank Activity
dan melanjutkannya hingga selesai.

activity_main.xml
Tampilan untuk container floating action button.

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


<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.dedykuncoro.kuncorocrud.MainActivity">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml
Sebagai tampilan dari data-data pada listview.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.dedykuncoro.kuncorocrud.MainActivity"
tools:showIn="@layout/activity_main">

<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ListView
android:id="@+id/list"
android:divider="@color/list_divider"
android:dividerHeight="2dp"
android:listSelector="@drawable/list_row_selector"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

list_row.xml
Sebagai tampilan custom listview yang berisi nama dan alamat.

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>

<TextView
android:id="@+id/nama"
android:layout_marginBottom="5dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

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

</LinearLayout>

form_biodata.xml
Tampilan untuk mengisi biodata.

<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<EditText
android:id="@+id/txt_id"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background_normal"/>

<EditText
android:id="@+id/txt_nama"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:hint="Nama"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background_normal"/>

<EditText
android:id="@+id/txt_alamat"
android:layout_marginBottom="10dp"
android:hint="Alamat"
android:inputType="textMultiLine"
android:minLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background_normal"/>

</LinearLayout>

Buat folder drawable didalam res dan isi file baru dengan nama list_row_bg.xml,
list_row_bg_hover.xml, dan list_row_selector.xml sebagai style listview.
list_row_bg.xml

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@color/list_row_start_color"
android:endColor="@color/list_row_end_color"
android:angle="270" />
</shape>

list_row_bg_hover.xml

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
android:angle="270"
android:endColor="@color/list_row_hover_end_color"
android:startColor="@color/list_row_hover_start_color" />

</shape>

list_row_selector.xml

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/list_row_bg"
android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/list_row_bg_hover"
android:state_pressed="true"/>
<item android:drawable="@drawable/list_row_bg_hover"
android:state_pressed="false" android:state_selected="true"/>

</selector>
Masuk folder res=>values=>color.xml dan tambahkan code seperti berikut :
color.xml

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


<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="list_divider">#d9d9d9</color>
<color name="list_row_start_color">#ffffff</color>
<color name="list_row_end_color">#ffffff</color>
<color name="list_row_hover_start_color">#ebeef0</color>
<color name="list_row_hover_end_color">#ebeef0</color>
</resources>

Buka build.gradle dan tambahkan volley library didalamnya.

1 compile 'com.mcxiaoke.volley:library-aar:1.0.0'

build.gradle

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0' /*tambahan volley
library*/
}

Agar project terstruktur dan terorganisir, buat 4 paket dengan nama adapter, app, data, dan
util. Untuk membuat paket baru , klik kanan pada src=>New=>Peckage dan memberikan
nama paket . Contoh : com.dedykuncoro.kuncorocrud.
Buat class AppController.java didalam package app dan tambah coding seperti dibawah ini.
Class tunggal yang menginisialisasi class global yang diperlukan. Semua objek yang
berhubungan dengan volley diinisialisasi di sini.
AppController.java

package com.dedykuncoro.kuncorocrud.app;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
* Created by Kuncoro on 26/03/2016.
*/
public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}

public static synchronized AppController getInstance() {


return mInstance;
}

public RequestQueue getRequestQueue() {


if (mRequestQueue == null) {
mRequestQueue =
Volley.newRequestQueue(getApplicationContext());
}

return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {


req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {


req.setTag(TAG);
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {


if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}

Buat class Data.java didalam package data dan tambahkan coding seperti dibawah ini. Class
ini berfungsi sebagai membuat objek untuk setiap item yang diparsing JSON. Objek ini berisi
informasi seperti id, nama, dan alamat.
Data.java

package com.dedykuncoro.kuncorocrud.data;

/**
* Created by Kuncoro on 26/03/2016.
*/
public class Data {
private String id, nama, alamat;

public Data() {
}

public Data(String id, String nama, String alamat) {


this.id = id;
this.nama = nama;
this.alamat = alamat;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public String getNama() {


return nama;
}

public void setNama(String nama) {


this.nama = nama;
}

public String getAlamat() {


return alamat;
}

public void setAlamat(String alamat) {


this.alamat = alamat;
}
}
Buat class Adapter.java didalam package adapter dan tambahkan coding seperti dibawah ini.
Class ini berfungsi sebagai menampilkan data seperti id, nama, dan alamat kemudian
ditampilkan ke dalam listview.
Adapter.java

package com.dedykuncoro.kuncorocrud.adapter;

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

import com.dedykuncoro.kuncorocrud.R;
import com.dedykuncoro.kuncorocrud.app.AppController;
import com.dedykuncoro.kuncorocrud.data.Data;

import java.util.List;

/**
* Created by Kuncoro on 26/03/2016.
*/
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Data> items;

public Adapter(Activity activity, List<Data> items) {


this.activity = activity;
this.items = items;
}

@Override
public int getCount() {
return items.size();
}

@Override
public Object getItem(int location) {
return items.get(location);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);

TextView id = (TextView) convertView.findViewById(R.id.id);


TextView nama = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);

Data data = items.get(position);

id.setText(data.getId());
nama.setText(data.getNama());
alamat.setText(data.getAlamat());

return convertView;
}

Buat class Server.java didalam package util dan tambahkan coding seperti dibawah ini.
Class ini berfungsi mengatur link server sumber data dari web service yang akan digunakan.
Server.java

package com.dedykuncoro.kuncorocrud.util;

/**
* Created by Kuncoro on 26/03/2016.
*/
public class Server {
// sesuaikan dengan IP Address PC/laptop atau ip address emulator
android 10.0.2.2
public static final String URL =
"http://192.168.43.173/android/kuncoro_crud/";
}

Buka class MainActivity.java dan tambahkan coding seperti dibawah ini. Class ini berfungsi
menampilkan data biodata dalam listview dari web service volley JsonArrayRequest.
Setelah diparsing, semua data JSON Array akan disimpan pada objek Data. Terakhir
memanggil notifyDataSetChanged() untuk perubahan data pada Adapter. Fungsi insert,
update, delete, select, dan menampilkan form biodata juga ada didalam class ini.
MainActivity.java

package com.dedykuncoro.kuncorocrud;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.dedykuncoro.kuncorocrud.adapter.Adapter;
import com.dedykuncoro.kuncorocrud.app.AppController;
import com.dedykuncoro.kuncorocrud.data.Data;
import com.dedykuncoro.kuncorocrud.util.Server;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements


SwipeRefreshLayout.OnRefreshListener {

Toolbar toolbar;
FloatingActionButton fab;
ListView list;
SwipeRefreshLayout swipe;
List<Data> itemList = new ArrayList<Data>();
Adapter adapter;
int success;
AlertDialog.Builder dialog;
LayoutInflater inflater;
View dialogView;
EditText txt_id, txt_nama, txt_alamat;
String id, nama, alamat;

private static final String TAG = MainActivity.class.getSimpleName();

private static String url_select = Server.URL + "select.php";


private static String url_insert = Server.URL + "insert.php";
private static String url_edit = Server.URL + "edit.php";
private static String url_update = Server.URL + "update.php";
private static String url_delete = Server.URL + "delete.php";

public static final String TAG_ID = "id";


public static final String TAG_NAMA = "nama";
public static final String TAG_ALAMAT = "alamat";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
String tag_json_obj = "json_obj_req";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

// menghubungkan variablel pada layout dan pada java


fab = (FloatingActionButton) findViewById(R.id.fab_add);
swipe = (SwipeRefreshLayout)
findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list);

// untuk mengisi data dari JSON ke dalam adapter


adapter = new Adapter(MainActivity.this, itemList);
list.setAdapter(adapter);

// menamilkan widget refresh


swipe.setOnRefreshListener(this);

swipe.post(new Runnable() {
@Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
}
);

// fungsi floating action button memanggil form biodata


fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DialogForm("", "", "", "SIMPAN");
}
});

// listview ditekan lama akan menampilkan dua pilihan edit atau


delete data
list.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {

@Override
public boolean onItemLongClick(final AdapterView<?> parent, View
view,
final int position, long id) {
// TODO Auto-generated method stub
final String idx = itemList.get(position).getId();

final CharSequence[] dialogitem = {"Edit", "Delete"};


dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(true);
dialog.setItems(dialogitem, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case 0:
edit(idx);
break;
case 1:
delete(idx);
break;
}
}
}).show();
return false;
}
});

@Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}

// untuk mengosongi edittext pada form


private void kosong(){
txt_id.setText(null);
txt_nama.setText(null);
txt_alamat.setText(null);
}

// untuk menampilkan dialog from biodata


private void DialogForm(String idx, String namax, String alamatx, String
button) {
dialog = new AlertDialog.Builder(MainActivity.this);
inflater = getLayoutInflater();
dialogView = inflater.inflate(R.layout.form_biodata, null);
dialog.setView(dialogView);
dialog.setCancelable(true);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Form Biodata");

txt_id = (EditText) dialogView.findViewById(R.id.txt_id);


txt_nama = (EditText) dialogView.findViewById(R.id.txt_nama);
txt_alamat = (EditText) dialogView.findViewById(R.id.txt_alamat);

if (!idx.isEmpty()){
txt_id.setText(idx);
txt_nama.setText(namax);
txt_alamat.setText(alamatx);
} else {
kosong();
}

dialog.setPositiveButton(button, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
id = txt_id.getText().toString();
nama = txt_nama.getText().toString();
alamat = txt_alamat.getText().toString();

simpan_update();
dialog.dismiss();
}
});

dialog.setNegativeButton("BATAL", new
DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
kosong();
}
});

dialog.show();
}

// untuk menampilkan semua data pada listview


private void callVolley(){
itemList.clear();
adapter.notifyDataSetChanged();
swipe.setRefreshing(true);

// membuat request JSON


JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());

// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);

Data item = new Data();

item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));

// menambah item ke array


itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}

// notifikasi adanya perubahan data pada adapter


adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});

// menambah request ke request queue


AppController.getInstance().addToRequestQueue(jArr);
}

// fungsi untuk menyimpan atau update


private void simpan_update() {
String url;
// jika id kosong maka simpan, jika id ada nilainya maka update
if (id.isEmpty()){
url = url_insert;
} else {
url = url_update;
}

StringRequest strReq = new StringRequest(Request.Method.POST, url,


new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

// Cek error node pada json


if (success == 1) {
Log.d("Add/update", jObj.toString());

callVolley();
kosong();

Toast.makeText(MainActivity.this,
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();

} else {
Toast.makeText(MainActivity.this,
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(),
Toast.LENGTH_LONG).show();
}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters ke post url
Map<String, String> params = new HashMap<String, String>();
// jika id kosong maka simpan, jika id ada nilainya maka
update
if (id.isEmpty()){
params.put("nama", nama);
params.put("alamat", alamat);
} else {
params.put("id", id);
params.put("nama", nama);
params.put("alamat", alamat);
}

return params;
}

};

AppController.getInstance().addToRequestQueue(strReq,
tag_json_obj);
}

// fungsi untuk get edit data


private void edit(final String idx){
StringRequest strReq = new StringRequest(Request.Method.POST,
url_edit, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

// Cek error node pada json


if (success == 1) {
Log.d("get edit data", jObj.toString());
String idx = jObj.getString(TAG_ID);
String namax = jObj.getString(TAG_NAMA);
String alamatx = jObj.getString(TAG_ALAMAT);

DialogForm(idx, namax, alamatx, "UPDATE");

adapter.notifyDataSetChanged();

} else {
Toast.makeText(MainActivity.this,
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(),
Toast.LENGTH_LONG).show();
}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters ke post url
Map<String, String> params = new HashMap<String, String>();
params.put("id", idx);

return params;
}

};

AppController.getInstance().addToRequestQueue(strReq,
tag_json_obj);
}

// fungsi untuk menghapus


private void delete(final String idx){
StringRequest strReq = new StringRequest(Request.Method.POST,
url_delete, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());

try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);

// Cek error node pada json


if (success == 1) {
Log.d("delete", jObj.toString());

callVolley();

Toast.makeText(MainActivity.this,
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

adapter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this,
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(),
Toast.LENGTH_LONG).show();
}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters ke post url
Map<String, String> params = new HashMap<String, String>();
params.put("id", idx);

return params;
}

};

AppController.getInstance().addToRequestQueue(strReq,
tag_json_obj);
}

Tambahkan perijinan INTERNET, ACCESS_NETWORK_STATE,


android:name=.app.AppController pada application.
AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dedykuncoro.kuncorocrud">

<uses-permission android:name="android.permission.INTERNET" /> <!--


tambahan -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/> <!-- tambahan -->

<application
android:name=".app.AppController" <!-- tambahan -->
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>