Assalamualiqum sahabat blogger ☺
Sebelumnya saya sudah membahas tentang android, kali ini yang akan saya bagikan masih seputar tentang android juga yaitu membuat client-server. Ok langsung saja kita ke TKP :D
- Pertama buat database “Pakaian” pada PhpMyAdmin maka kita harus aktifkan Xampp terlebih dahulu.
- Kemudian buat table “db_pakaian” dengan struktur berikut:
- Selanjutnya buat file “server.php” dan simpan di folder C:\xampp\htdocs\pakaian. File ini berfungsi sebagai server.
<?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_pakaian
WHERE 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 WHERE
id='$id'");
if ($query_delete_pakaian) {
echo "Delete Data Berhasil";
} else {
echo mysql_error();
}
break;
default:
break;
}
?>
- Berikutnya buka eclipse ADT dan buat project android baru dengan nama “Pakaian”. Pada folder src buat tiga class baru dengan nama “Koneksi.java”, “MainActivity.java”, “Pakaian.java”
Buat pula file activity_main.xml untuk coding tampilannya:
- Berikut coding untuk file Koneksi.java
package com.example.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;
}
}
- Coding untuk MainActivity.java
package com.example.pakaian;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.pakaian.MainActivity;
import com.example.pakaian.Pakaian;
import com.example.pakaian.R;
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.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.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();
}
}
- Coding untuk Pakaian.java
Untuk IP Addressnya sesuaikan dengan IP server.
package com.example.pakaian;
public class Pakaian extends Koneksi {
String URL = "http://192.168.100.59/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;
}
}
- Coding untuk activity_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"
tools:context=".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 >
- Langkah terakhir tambahkan coding berikut pada file AndroidManifest.xml yang fungsinya berupa izin akses ke internet.
- Selanjutnya tinggal running project dan uji coba menambah data. Jika berhasil data yang kita inputkan dari android akan tersimpan di server.
Selamat mencoba ☺
0 komentar:
Posting Komentar