Crud Input Dengan JSON Dan Database MYSQL
Langka Awal Buatkan file php dengan nama server.php
Langka ketiga buatkan file dengan nama activity_main.xml
Langka Kelima buatkan file dengan nama Pakaian.java
package com.pakaian.pakaian;
public class Pakaian extends Koneksi {
String URL = "http://192.168.43.94/pakaian/server.php";
String url = "";
String response = "";
public String tampilPakaian() {
try {
url = URL + "?operasi=view";
System.out.println("URL Tampil Pakaian: " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String inserPakaian(String merk, String jenis,String ukuran, String harga) {
try {
url = URL + "?operasi=insert&merk=" + merk + "&jenis=" + jenis+ "&ukuran=" + ukuran+ "&harga=" + harga;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String getPakaianById(int id) {
try {
url = URL + "?operasi=get_pakaian_by_id&id=" + id;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String updatePakaian(String id, String merk, String jenis, String ukuran, String harga) {
try {
url = URL + "?operasi=update&id=" + id + "&merk=" + merk + "&jenis=" + jenis + "&ukuran=" + ukuran + "&harga=" + harga;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String deletePakaian(int id) {
try {
url = URL + "?operasi=delete&id=" + id;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
}
Langka Keenam buatkan file dengan nama MainActivity.java
Dan Outputnya akan jadi seperti di bawah ini
Hasil database
Langka Kedua Edit AndroidManifest.xml seperti di bawah ini<?php $server = "localhost"; $username = "root"; $password = ""; $database = "pakaian"; mysql_connect($server, $username, $password) or die("<h1>Koneksi Mysql Error :</h1>" . mysql_error()); mysql_select_db($database) or die("<h1>Koneksi Kedatabase Error : </h1>" .mysql_error()); @$operasi = $_GET['operasi']; switch ($operasi) { case "view": $query_tampil_pakaian = mysql_query("SELECT * FROM db_pakaian")or die(mysql_error()); $data_array = array(); while ($data = mysql_fetch_assoc($query_tampil_pakaian)) { $data_array[] = $data; } echo json_encode($data_array); break; case "insert": /* Source code untuk Insert data */ @$merk = $_GET['merk']; @$jenis = $_GET['jenis']; @$ukuran = $_GET['ukuran']; @$harga = $_GET['harga']; $query_insert_data = mysql_query("INSERT INTO db_pakaian(merk, jenis, ukuran, harga) VALUES('$merk', '$jenis', '$ukuran', '$harga')"); if ($query_insert_data) { echo "Data Berhasil Disimpan"; } else { echo "Error Insert Pakaian " . mysql_error(); } break; case "get_pakaian_by_id": @$id = $_GET['id']; $query_tampil_pakaian = mysql_query("SELECT * FROM db_pakaianWHERE id='$id'") or die(mysql_error()); $data_array = array(); $data_array = mysql_fetch_assoc($query_tampil_pakaian); echo "[" . json_encode($data_array) . "]"; break; case "update": /* Source code untuk Update Biodata */ @$merk = $_GET['merk']; @$jenis = $_GET['jenis']; @$ukuran = $_GET['ukuran']; @$harga = $_GET['harga']; @$id = $_GET['id']; $query_update_pakaian = mysql_query("UPDATE db_pakaian SET merk='$merk',jenis='$jenis' , ukuran='$ukuran',harga='$harga' WHERE id='$id'"); if ($query_update_pakaian) { echo "Update Data Berhasil"; } else { echo mysql_error(); } break; case "delete": /* Source code untuk Delete Biodata */ @$id = $_GET['id']; $query_delete_pakaian = mysql_query("DELETE FROM db_pakaian WHEREid='$id'"); if ($query_delete_pakaian) { echo "Delete Data Berhasil"; } else { echo mysql_error(); } break; default: break; } ?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jhohannes.purba"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="jhohannes.purba.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> Langka ketiga buatkan file dengan nama activity_main.xml
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"Langka Keempat Buatkan file dengan nama Koneksi.java
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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="com.examplore.deathnote.MainActivity" >
<Button
android:id="@+id/buttonTambahPakaian"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Tambah Pakaian" />
<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/tablePakaian"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
</TableLayout>
</ScrollView>
</HorizontalScrollView>
</LinearLayout>
package com.examplore.deathnote;
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;
}
}
Langka Kelima buatkan file dengan nama Pakaian.java
package com.pakaian.pakaian;
public class Pakaian extends Koneksi {
String URL = "http://192.168.43.94/pakaian/server.php";
String url = "";
String response = "";
public String tampilPakaian() {
try {
url = URL + "?operasi=view";
System.out.println("URL Tampil Pakaian: " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String inserPakaian(String merk, String jenis,String ukuran, String harga) {
try {
url = URL + "?operasi=insert&merk=" + merk + "&jenis=" + jenis+ "&ukuran=" + ukuran+ "&harga=" + harga;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String getPakaianById(int id) {
try {
url = URL + "?operasi=get_pakaian_by_id&id=" + id;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String updatePakaian(String id, String merk, String jenis, String ukuran, String harga) {
try {
url = URL + "?operasi=update&id=" + id + "&merk=" + merk + "&jenis=" + jenis + "&ukuran=" + ukuran + "&harga=" + harga;
System.out.println("URL Insert Biodata : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
public String deletePakaian(int id) {
try {
url = URL + "?operasi=delete&id=" + id;
System.out.println("URL Insert Pakaian : " + url);
response = call(url);
} catch (Exception e) {
}
return response;
}
}
Langka Keenam buatkan file dengan nama MainActivity.java
package com.examplore.deathnote;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.examplore.deathnote.MainActivity;
import com.examplore.deathnote.Pakaian;
import com.examplore.deathnote.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
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 {
Pakaian pakaian = new Pakaian();
TableLayout tabelPakaian;
Button buttonTambahPakaian;
ArrayList<Button> buttonEdit = new ArrayList<Button>();
ArrayList<Button> buttonDelete = new ArrayList<Button>();
JSONArray arrayPakaian;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//pengenalan variabel
tabelPakaian = (TableLayout) findViewById(R.id.tablePakaian);
buttonTambahPakaian = (Button) findViewById(R.id.buttonTambahPakaian);
buttonTambahPakaian.setOnClickListener(this);
TableRow barisTabel = new TableRow(this);
barisTabel.setBackgroundColor(Color.CYAN);
TextView viewHeaderId = new TextView(this);
TextView viewHeaderMerk = new TextView(this);
TextView viewHeaderJenis = new TextView(this);
TextView viewHeaderUkuran = new TextView(this);
TextView viewHeaderHarga = new TextView(this);
TextView viewHeaderAction = new TextView(this);
viewHeaderId.setText("ID");
viewHeaderMerk.setText("Merk");
viewHeaderJenis.setText("Jenis");
viewHeaderUkuran.setText("Ukuran");
viewHeaderHarga.setText("Harga");
viewHeaderAction.setText("Action");
viewHeaderId.setPadding(5, 1, 5, 1);
viewHeaderMerk.setPadding(5, 1, 5, 1);
viewHeaderJenis.setPadding(5, 1, 5, 1);
viewHeaderUkuran.setPadding(5, 1, 5, 1);
viewHeaderHarga.setPadding(5, 1, 5, 1);
viewHeaderAction.setPadding(5, 1, 5, 1);
barisTabel.addView(viewHeaderId);
barisTabel.addView(viewHeaderMerk);
barisTabel.addView(viewHeaderJenis);
barisTabel.addView(viewHeaderUkuran);
barisTabel.addView(viewHeaderHarga);
barisTabel.addView(viewHeaderAction);
tabelPakaian.addView(barisTabel, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
try {
arrayPakaian = new JSONArray(pakaian.tampilPakaian());
for (int i = 0; i < arrayPakaian.length(); i++) {
JSONObject jsonChildNode = arrayPakaian.getJSONObject(i);
String merk = jsonChildNode.optString("merk");
String jenis = jsonChildNode.optString("jenis");
String ukuran = jsonChildNode.optString("ukuran");
String harga = jsonChildNode.optString("harga");
String id = jsonChildNode.optString("id");
System.out.println("Merk :" + merk);
System.out.println("Jenis :" + jenis);
System.out.println("Ukuran :" + ukuran);
System.out.println("Harga :" + harga);
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 viewMerk = new TextView(this);
viewMerk.setText(merk);
viewMerk.setPadding(5, 1, 5, 1);
barisTabel.addView(viewMerk);
TextView viewJenis = new TextView(this);
viewJenis.setText(jenis);
viewJenis.setPadding(5, 1, 5, 1);
barisTabel.addView(viewJenis);
TextView viewUkuran = new TextView(this);
viewUkuran.setText(ukuran);
viewUkuran.setPadding(5, 1, 5, 1);
barisTabel.addView(viewUkuran);
TextView viewHarga = new TextView(this);
viewHarga.setText(harga);
viewHarga.setPadding(5, 1, 5, 1);
barisTabel.addView(viewHarga);
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));
tabelPakaian.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.buttonTambahPakaian) {
// Toast.makeText(MainActivity.this, "Button Tambah Data",
// Toast.LENGTH_SHORT).show();
tambahPakaian();
} 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();
deletePakaian(id);
}
}
}
}
public void deletePakaian(int id) {
pakaian.deletePakaian(id);
/* restart acrtivity */
finish();
startActivity(getIntent());
}
public void getDataByID(int id) {
String merkEdit = null, jenisEdit = null, ukuranEdit = null, hargaEdit = null;
JSONArray arrayPersonal;
try {
arrayPersonal = new JSONArray(pakaian.getPakaianById(id));
for (int i = 0; i < arrayPersonal.length(); i++) {
JSONObject jsonChildNode = arrayPersonal.getJSONObject(i);
merkEdit = jsonChildNode.optString("merk");
jenisEdit = jsonChildNode.optString("jenis");
ukuranEdit = jsonChildNode.optString("ukuran");
hargaEdit = jsonChildNode.optString("harga");
}
} 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 editMerk = new EditText(this);
editMerk.setText(merkEdit);
layoutInput.addView(editMerk);
final EditText editJenis = new EditText(this);
editJenis.setText(jenisEdit);
layoutInput.addView(editJenis);
final EditText editUkuran = new EditText(this);
editUkuran.setText(ukuranEdit);
layoutInput.addView(editUkuran);
final EditText editHarga = new EditText(this);
editHarga.setText(hargaEdit);
layoutInput.addView(editHarga);
AlertDialog.Builder builderEditPakaian = new AlertDialog.Builder(this);
builderEditPakaian.setIcon(R.drawable.batagrams);
builderEditPakaian.setTitle("Update Pakaian");
builderEditPakaian.setView(layoutInput);
builderEditPakaian.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String merk = editMerk.getText().toString();
String jenis = editJenis.getText().toString();
String ukuran = editUkuran.getText().toString();
String harga = editHarga.getText().toString();
System.out.println("Merk : " + merk + " Jenis : " + jenis+ " Ukuran : " + ukuran+ " Harga : " + harga);
String laporan = pakaian.updatePakaian(viewId.getText().toString(), editMerk.getText().toString(),
editJenis.getText().toString(),editUkuran.getText().toString(), editHarga.getText().toString());
Toast.makeText(MainActivity.this, laporan, Toast.LENGTH_SHORT).show();
/* restart acrtivity */
finish();
startActivity(getIntent());
}
});
builderEditPakaian.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderEditPakaian.show();
}
public void tambahPakaian() {
/* layout akan ditampilkan pada AlertDialog */
LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);
final EditText editMerk = new EditText(this);
editMerk.setHint("Merk");
layoutInput.addView(editMerk);
final EditText editJenis = new EditText(this);
editJenis.setHint("Jenis");
layoutInput.addView(editJenis);
final EditText editUkuran = new EditText(this);
editUkuran.setHint("Ukuran");
layoutInput.addView(editUkuran);
final EditText editHarga = new EditText(this);
editHarga.setHint("Harga");
layoutInput.addView(editHarga);
AlertDialog.Builder builderInsertPakaian = new AlertDialog.Builder(this);
builderInsertPakaian.setIcon(R.drawable.batagrams);
builderInsertPakaian.setTitle("Insert Pakaian");
builderInsertPakaian.setView(layoutInput);
builderInsertPakaian.setPositiveButton("Insert", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String merk = editMerk.getText().toString();
String jenis = editJenis.getText().toString();
String ukuran = editUkuran.getText().toString();
String harga = editHarga.getText().toString();
System.out.println("Merk : " + merk + " Jenis : " + jenis+ " Ukuran : " + ukuran+ " Harga : " + harga);
String laporan = pakaian.inserPakaian(merk, jenis, ukuran, harga);
Toast.makeText(MainActivity.this, laporan, Toast.LENGTH_SHORT).show();
/* restart acrtivity */
finish();
startActivity(getIntent());
}
});
builderInsertPakaian.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderInsertPakaian.show();
}
}
Dan Outputnya akan jadi seperti di bawah ini
Hasil database
Hasil Output dari Android
Komentar
Posting Komentar