LATIHAN ANDROID DATABASES part 03
Pada laporan ke-dua kali ini, saya akan menjelaskan tentang client server Persiapan :
A. Database
è Buka localhost/phpmyadmin
è Buat database dengan nama pakaian
B. PHP
è Buka folder htdocs ( C : xampp/htdocs )
è Buat sebuah folder bernama pakaian
è di dalam folder server, buat sebuah file dengan nama index.php
C. Android
è Buat sebuah project (File -> New Android Application) dan beri nama pakaian è Pada lokasi src pastikan sudah ada file :
a. MainActivity.java
b. Koneksi.Java
c. Pakaian.java
Database
Ekseskusi query ini untuk membuat tabel_biodata
Jika dibrowse, maka hasilnya akan kelihatan seperti gambar berikut :
PHP - index.php
Buka server.php yang berada di lokasi C:\xampp\htdocs\server\index.php, lalu ketikkan source code berikut :
<form method="post" action="simpan_data.php">
<table border="0" align="center">
<tr>
<td colspan="5" align="center"><h2>From Inputan</h2></td>
</tr>
<tr>
<td>Merk</td>
<td>:</td>
<td><input type="text" name="merk"/></td>
</tr>
<tr>
<td>Jenis</td>
<td>:</td>
<td><input type="text" name="jenis"/></td>
</tr>
<tr>
<td>Ukuran</td>
<td>:</td>
<td><input type="text" name="ukuran"/></td>
</tr>
<tr>
<td>Harga</td>
<td>:</td>
<td><input type="number" name="harga"/></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Simpan"/>
<input type="reset" value="Reset"/></td>
</tr>
</table>
</form>
Android
Android - main.xml
<LinearLayout 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" android:orientation="vertical"
tools:context="com.examplore.deathnote.MainActivity" >
<Button
android:id="@+id/buttonTambahPakaian" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Tambah Data Loundry" />
<HorizontalScrollView
android:id="@+id/horizontalScrollView" android:layout_width="fill_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>
Android - class.java
MainActivity,java
package com.is.pakaian;
import java.util.ArrayList;
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
import android.annotation.SuppressLint; 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;
@SuppressLint("NewApi") 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.ic_launcher); 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.ic_launcher); 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();
}
}
Koneksi,java
package com.is.pakaian;
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;
}
}
Pakaian.java
package com.is.pakaian;
public class Pakaian extends Koneksi {
String URL = "http://10.0.2.2/Server/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;
}
}
Untuk hasil running bisa lihat gambar di bawah ini…
Inilah hasil running project.
Gambar di atas yang ditandai dengan warna kuning, merupakan hasil dari inputan tadi.. jadi, secara otomatis data tersebut akan tersimpan di database dan server. Lihat 2 gambar di bawah ini.
Selesai.. maaf jika tampilannya kurang cantik, anda bisa memperindah tampilannya dengan CSS <HTML> dan lain sebagainya…
Komentar
Posting Komentar