Anda di halaman 1dari 36

Tutorial Mysql Android Eclipse

Buatlah database dengan nama db_universitas dan table mahasiswa dengan field sebagai
berikut :

Isi datanya sebanyak 4 buah untuk percobaan.

Untuk beriikutnya buatlah project (folder) di htdocs dengan nama mahasiswa dan
tambahkan file-file berikut :

1. db_connect.php

<?php

$connect = new mysqli("localhost", "root", "", "db_universitas");


if(!$connect)
{
echo "Koneksi Gagal";
exit();
}
?>

2. getAllMahasiswa.php

<?php

$response = array();

require_once __DIR__ . '/db_connect.php';

$result = $connect->query("SELECT *FROM mahasiswa");

if (mysqli_num_rows($result) > 0) {

$response["mahasiswa"] = array();

while ($row = mysqli_fetch_array($result)) {

Tutorial Android Mysql | Muharir.,M.Kom


$mahasiswa = array();
$mahasiswa["id"] = $row["id"];
$mahasiswa["npm"] = $row["npm"];
$mahasiswa["nama"] = $row["nama"];
$mahasiswa["kelas"] = $row["kelas"];
$mahasiswa["alamat"] = $row["alamat"];

array_push($response["mahasiswa"], $mahasiswa);
}
$response["success"] = 1;

echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Tidak ada data yang ditemukan";

echo json_encode($response);
}
?>

3. get_mahasiswa_details.php

<?php

$response = array();

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();

if (isset($_GET["id"]))
{

$id = $_GET['id'];

$result = mysql_query("SELECT *FROM mahasiswa WHERE id = $id");


if (!empty($result))
{
if (mysql_num_rows($result) > 0)
{
$result = mysql_fetch_array($result);
$mahasiswa = array();

Tutorial Android Mysql | Muharir.,M.Kom


$mahasiswa["id"] = $result["id"];
$mahasiswa["npm"] = $result["npm"];
$mahasiswa["nama"] = $result["nama"];
$mahasiswa["kelas"] = $result["kelas"];
$mahasiswa["alamat"] = $result["alamat"];

$response["success"] = 1;

$response["mahasiswa"] = array();
array_push($response["mahasiswa"], $mahasiswa);
echo json_encode($response);
} else {

$response["success"] = 0;
$response["message"] = "Tidak ada data";

echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Tidak ada data";

echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Silahkan lengkapi permintaan anda";

echo json_encode($response);
}
?>

4. create_mahasiswa.php

<?php

$response = array();

if (isset($_POST['npm']) && isset($_POST['nama']) && isset($_POST['ke


las']) && isset($_POST['alamat'])) {

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

Tutorial Android Mysql | Muharir.,M.Kom


$kelas = $_POST['kelas'];
$alamat = $_POST['alamat'];
require_once __DIR__ . '/db_connect.php';

$result = $connect-
>query("INSERT INTO mahasiswa(npm, nama, kelas, alamat) VALUES ('$npm
', '$nama', '$kelas', '$alamat')");

if ($result) {
$response["success"] = 1;
$response["message"] = "membuat data berhasil";

echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Sistem mendeteksi kesalahan, silahkan
coba lagi";

echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Silahkan lengkapi aksi sebelum memulai pe
rmintaan anda";

echo json_encode($response);
}
?>

5. update_mahasiswa.php

<?php

$response = array();

if (isset($_POST['id']) && isset($_POST['npm']) && isset($_POST['nama


']) && isset($_POST['kelas']) && isset($_POST['alamat'])) {

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

Tutorial Android Mysql | Muharir.,M.Kom


require_once __DIR__ . '/db_connect.php';

$result = $connect-
>query("UPDATE mahasiswa SET npm = '$npm', nama = '$nama', kelas = '$
kelas', alamat = '$alamat' WHERE id = $id");

if ($result)
{
$response["success"] = 1;
$response["message"] = "Data anda berhasil di perbarui";
echo json_encode($response);
}
else
{

}
}
else
{
$response["success"] = 0;
$response["message"] = "Mohon kelengkapan data anda";
echo json_encode($response);
}
?>

6. delete_mahasiswa.php

<?php

$response = array();

if (isset($_POST['id']))
{
$id = $_POST['id'];

require_once __DIR__ . '/db_connect.php';

$result = $connect-
>query("DELETE FROM mahasiswa WHERE id = $id");

if ($connect->affected_rows() > 0)
{
$response["success"] = 1;

Tutorial Android Mysql | Muharir.,M.Kom


$response["message"] = "Data berhasil di hapus";

echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Tidak ada data yang tersedia";

echo json_encode($response);
}
}
else
{
$response["success"] = 0;
$response["message"] = "Aksi tidak bisa di lakukan";
echo json_encode($response);
}
?>

Untuk mengeceknya apakah sudah benar koding yang dibuat diphp, kita bisa mengeceknya
dengan menginstall postman pada web berikut. https://www.getpostman.com/

Jika sudah jalankan dan akses endpoint berikut :

Tutorial Android Mysql | Muharir.,M.Kom


Jika data sudah muncul, bisa dipastikan script yang anda buat sudah benar.

Berikutnya konfigurasilah handphone anda dengan membuat thetering USB dan check IP
yang didapatkan pada komputer. Buka cmd pada komputer dan ketikkan ipconfig.

Ip diatas di dapatkan saat tethering USB dari handphone ke laptop/computer, setiap


handpone punya ip yang berbeda jadi anda bisa mengeceknya dengan menggunakan
perintah ipconfig pada command prompt. Dan cek pada tulisan Ethernet Adapter.

Buat project baru di eclipse dengan nama AndroidMysql

Ingat pastikan gunakan API 17 agar compiling code berhasil.

Tutorial Android Mysql | Muharir.,M.Kom


Untuk Activity pilih Blank Activity – Next – Finish.

Buatlah Activity dan Layout baru dengan cara Klik Kanan Project – New – Other – Android
Activity – Empty Activity

Pada popup menu masukkan isian berikut

Tutorial Android Mysql | Muharir.,M.Kom


Klik finish.

Buat Activity Baru Seperti pada step sebelumnya dan pada popup menu masukkan isian
seperti berikut :

Berikutnya pada project klik kanan Pilih Android XML Layout.

Tutorial Android Mysql | Muharir.,M.Kom


Pada kolom File berinama komponendata

Pada activity_main.xml buat kode seperti berikut :


<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="com.uniska.androidmysql.MainActivity" >

<TextView

Tutorial Android Mysql | Muharir.,M.Kom


android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Data Mahasiswa"
android:textSize="20dp" />

<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_weight="0.27" >

</ListView>

<Button
android:id="@+id/btnTambah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@android:id/list"
android:layout_alignParentBottom="true"
android:layout_alignRight="@android:id/list"
android:layout_marginBottom="16dp"
android:text="Tambah Data Siswa" />

</RelativeLayout>

Sehingga pada graphical layout activity_main.xml akan tampak tampilan seperti berikut :

Tutorial Android Mysql | Muharir.,M.Kom


activity_tambah.xml
<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="${relativePackage}.${activityClass}" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Tambah Mahasiswa"
android:textSize="20dp" />

<EditText
android:id="@+id/editNPM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:ems="10"
android:hint="NPM"/>

<EditText
android:id="@+id/editNAMA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editNPM"
android:layout_alignRight="@+id/editNPM"
android:layout_below="@+id/editNPM"
android:ems="10"
android:hint="NAMA" />

<EditText
android:id="@+id/editKELAS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editNAMA"
android:layout_alignRight="@+id/editNAMA"
android:layout_below="@+id/editNAMA"
android:ems="10"
android:hint="KELAS" />

<EditText
android:id="@+id/editALAMAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editKELAS"

Tutorial Android Mysql | Muharir.,M.Kom


android:layout_centerVertical="true"
android:ems="13"
android:hint="Alamat"
android:lines="3" />

<Button
android:id="@+id/btnTambahData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editALAMAT"
android:layout_alignRight="@+id/editALAMAT"
android:layout_below="@+id/editALAMAT"
android:layout_marginTop="20dp"
android:text="Tambah Data" />

<Button
android:id="@+id/btnBatalkan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnTambahData"
android:layout_alignRight="@+id/btnTambahData"
android:layout_below="@+id/btnTambahData"
android:text="Kembali" />

</RelativeLayout>

Sehingga pada graphical layout activity_tambah.xml akan tampak tampilan seperti berikut

Tutorial Android Mysql | Muharir.,M.Kom


activity_edit_data.xml
<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="${relativePackage}.${activityClass}" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Edit Data Mahasiswa"
android:textSize="20dp" />

<EditText
android:id="@+id/editEDITNPM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:ems="10"
android:hint="NPM"/>

<EditText
android:id="@+id/editEDITALAMAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editKELAS"
android:layout_centerVertical="true"
android:ems="13"
android:hint="Alamat"
android:lines="3" />

<EditText
android:id="@+id/editEDITNAMA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editEDITNPM"
android:layout_alignRight="@+id/editEDITALAMAT"
android:layout_below="@+id/editEDITNPM"
android:ems="10"
android:hint="NAMA" />

<EditText
android:id="@+id/editEDITKELAS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editEDITNAMA"

Tutorial Android Mysql | Muharir.,M.Kom


android:layout_alignRight="@+id/editEDITALAMAT"
android:layout_below="@+id/editEDITNAMA"
android:ems="10"
android:hint="KELAS" />

<Button
android:id="@+id/btnEDITSIMPAN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editEDITALAMAT"
android:layout_alignRight="@+id/editEDITALAMAT"
android:layout_below="@+id/editEDITALAMAT"
android:text="S I M P A N" />

<Button
android:id="@+id/btnEDITHAPUS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnEDITSIMPAN"
android:layout_alignRight="@+id/btnEDITSIMPAN"
android:layout_below="@+id/btnEDITSIMPAN"
android:text="H A P U S" />

<Button
android:id="@+id/btnEDITKEMBALI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnEDITHAPUS"
android:layout_alignRight="@+id/btnEDITHAPUS"
android:layout_below="@+id/btnEDITHAPUS"
android:text="K E M B A L I" />

</RelativeLayout>

Sehingga pada graphical layout activity_edit_data.xml akan tampak tampilan seperti


berikut :

Tutorial Android Mysql | Muharir.,M.Kom


Terakhir pada komponendata.xml buat isi filenya menjadi berikut :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No\t\t\t\t\t\t\t\t\t:\t"
android:textSize="20dp"
android:textColor="@android:color/black"/>

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

Tutorial Android Mysql | Muharir.,M.Kom


android:text="TextView"
android:textSize="15dp"
android:textColor="@android:color/black" />
</TableRow>
</TableLayout>

<TableLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NISN\t\t\t\t\t\t\t\t:\t"
android:textSize="20dp"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/textNPM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15dp"
android:textColor="@android:color/black" />
</TableRow>
</TableLayout>

<TableLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NAMA\t\t\t\t\t\t\t:\t"
android:textSize="20dp"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/textNAMA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15dp"
android:textColor="@android:color/black" />
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout android:layout_width="fill_parent"

Tutorial Android Mysql | Muharir.,M.Kom


android:layout_height="fill_parent">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kelas\t\t\t\t\t\t\t:\t"
android:textSize="20dp"
android:textColor="@android:color/black" />

<TextView
android:id="@+id/textKELAS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15dp"
android:textColor="@android:color/black"/>

</TableRow>
</TableLayout>

<TableLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alamat\t\t\t\t\t\t:\t"
android:textSize="20dp"
android:textColor="@android:color/black"/>

<TextView
android:id="@+id/textALAMAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15dp"
android:textColor="@android:color/black"/>

</TableRow>
</TableLayout>

</LinearLayout>

</LinearLayout>

Tutorial Android Mysql | Muharir.,M.Kom


Gambar diatas adalah hasil dari komponendata.xml yang sebelumnya sudah kita tambahkan
kode.

Berikutnya tambahkan kelas JSONParser.java pada package project. Dengan cara klik kanan
package – class – JSONParser.java

Tutorial Android Mysql | Muharir.,M.Kom


JSONParser.java
package com.uniska.androidmysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;


static JSONObject jobj = null;
static String json = "";

public JSONParser() {

//function get json from url


//by making http POST or GET method
public JSONObject makeHTTPRequest(String url,
String method, List<NameValuePair> params) {

Tutorial Android Mysql | Muharir.,M.Kom


//Making HTTP request
try {
//check for request method
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();

} 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");
}

Tutorial Android Mysql | Muharir.,M.Kom


is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

try {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

return jobj;
}

MainActivity.java
package com.uniska.androidmysql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;

Tutorial Android Mysql | Muharir.,M.Kom


import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {


Button tambah;
private ProgressDialog pDialog;
Button kembali;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listsiswa1;

private static String url_semua_siswa = "http://10.0.3.2/mahasiswa/getAllMahasiswa.php";


private static final String TAG_SUCCESS = "success";
private static final String TAG_MAHASISWA = "mahasiswa";
private static final String TAG_ID = "id";
private static final String TAG_NPM = "npm";
private static final String TAG_NAMA = "nama";
private static final String TAG_KELAS = "kelas";
private static final String TAG_ALAMAT = "alamat";

JSONArray listsiswa = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listsiswa1 = new ArrayList<HashMap<String, String>>();
new LoadSemuaDataSiswa().execute();
tambah = (Button) findViewById(R.id.btnTambah);
tambah.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, TambahActivity.class);
startActivity(i);

}
});
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {

Tutorial Android Mysql | Muharir.,M.Kom


@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long pid) {
// TODO Auto-generated method stub
String id = ((TextView) view.findViewById(R.id.textID)).getText().toString();
Intent edit = new Intent(getApplicationContext(), EditDataActivity.class);
edit.putExtra(TAG_ID, id);
startActivityForResult(edit, 100);
}

});
}

class LoadSemuaDataSiswa extends AsyncTask<String, String, String>


{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Mohon tunggu, loading data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHTTPRequest(url_semua_siswa, "GET", param);
Log.d("Semua Daftar Makanan", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if(success == 1)
{
listsiswa = json.getJSONArray(TAG_MAHASISWA);
for(int i = 0; i < listsiswa.length(); i++)
{
JSONObject c = listsiswa.getJSONObject(i);

Tutorial Android Mysql | Muharir.,M.Kom


String id = c.getString(TAG_ID);
String npm = c.getString(TAG_NPM);
String nama = c.getString(TAG_NAMA);
String kelas = c.getString(TAG_KELAS);
String alamat = c.getString(TAG_ALAMAT);

HashMap<String, String> map = new HashMap<String, String>();

map.put(TAG_ID, id);
map.put(TAG_NPM, npm);
map.put(TAG_NAMA, nama);
map.put(TAG_KELAS, kelas);
map.put(TAG_ALAMAT, alamat);

listsiswa1.add(map);
}
}
else
{

}
}
catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
runOnUiThread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
ListAdapter adapter = new SimpleAdapter(MainActivity.this, listsiswa1,
R.layout.komponendata,
new String[] {TAG_ID, TAG_NPM, TAG_NAMA, TAG_KELAS, TAG_ALAMAT}, new
int[]

Tutorial Android Mysql | Muharir.,M.Kom


{R.id.textID, R.id.textNPM, R.id.textNAMA, R.id.textKELAS,
R.id.textALAMAT});
setListAdapter(adapter);
}
});
}
}
}

TambahActivity.java
package com.uniska.androidmysql;

import java.util.ArrayList;
import java.util.List;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class TambahActivity extends Activity {


private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();


private static String url_tambah_mahasiswa = "http://10.0.3.2/mahasiswa/create_mahasiswa.php";

private static final String TAG_SUCCESS = "success";


private static final String TAG_NPM = "npm";
private static final String TAG_NAMA = "nama";
private static final String TAG_KELAS = "kelas";

Tutorial Android Mysql | Muharir.,M.Kom


private static final String TAG_ALAMAT = "alamat";

EditText editADDNPM, editADDNAMA, editADDkelas, editADDALAMAT;


Button tambahdata, kembali;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah);

editADDNPM = (EditText) findViewById(R.id.editNPM);


editADDNAMA = (EditText) findViewById(R.id.editNAMA);
editADDkelas = (EditText) findViewById(R.id.editKELAS);
editADDALAMAT = (EditText) findViewById(R.id.editALAMAT);

tambahdata = (Button) findViewById(R.id.btnTambahData);


tambahdata.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TambahSiswa().execute();

}
});
kembali = (Button) findViewById(R.id.btnBatalkan);
kembali.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent kembali = new Intent(TambahActivity.this, MainActivity.class);
startActivity(kembali);

}
});
}
class TambahSiswa extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {

Tutorial Android Mysql | Muharir.,M.Kom


// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(TambahActivity.this);
pDialog.setMessage("Sedang membuat pendaftaran...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub

String npm = editADDNPM.getText().toString();


String nama = editADDNAMA.getText().toString();
String kelas = editADDkelas.getText().toString();
String alamat = editADDALAMAT.getText().toString();

List<NameValuePair> param = new ArrayList<NameValuePair>();

param.add(new BasicNameValuePair(TAG_NPM, npm));


param.add(new BasicNameValuePair(TAG_NAMA, nama));
param.add(new BasicNameValuePair(TAG_KELAS, kelas));
param.add(new BasicNameValuePair(TAG_ALAMAT, alamat));

JSONObject json = jsonParser.makeHTTPRequest(url_tambah_mahasiswa, "POST", param);


try{
int success = json.getInt(TAG_SUCCESS);
if(success ==1)
{
Intent tambah = new Intent(TambahActivity.this, MainActivity.class);
startActivity(tambah);
}
else
{

}
}
catch(JSONException e)
{
e.printStackTrace();

Tutorial Android Mysql | Muharir.,M.Kom


}
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
}

EditDataActivity.java
package com.uniska.androidmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditDataActivity extends Activity {

Tutorial Android Mysql | Muharir.,M.Kom


Button editsimpan, edithapus, editkembali;
EditText editENPM, editENAMA, editEKELAS, editEALAMAT;
String id;
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();


private static String url_mahasiswa_details = "http://10.0.3.2/mahasiswa/get_mahasiswa_details.php";
private static String url_update_mahasiswa = "http://10.0.3.2/mahasiswa/update_mahasiswa.php";
private static String url_delete_mahasiswa = "http://10.0.3.2/mahasiswa/delete_mahasiswa.php";

private static final String TAG_SUCCESS = "success";


private static final String TAG_MAHASISWA = "mahasiswa";
private static final String TAG_ID = "id";
private static final String TAG_NPM = "npm";
private static final String TAG_NAMA = "nama";
private static final String TAG_KELAS = "kelas";
private static final String TAG_ALAMAT = "alamat";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_data);

Intent i = getIntent();
id = i.getStringExtra(TAG_ID);
new GetSiswaDetails().execute();
editsimpan = (Button) findViewById(R.id.btnEDITSIMPAN);
editsimpan.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new UpdateSiswa().execute();
}
});
edithapus = (Button) findViewById(R.id.btnEDITHAPUS);
edithapus.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Tutorial Android Mysql | Muharir.,M.Kom


new DeleteSiswa().execute();
}
});
editkembali = (Button) findViewById(R.id.btnEDITKEMBALI);
editkembali.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(i);
}
});
}
class GetSiswaDetails extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(EditDataActivity.this);
pDialog.setMessage("Mengambil Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
int success;
try
{
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id", id));

Tutorial Android Mysql | Muharir.,M.Kom


JSONObject json = jsonParser.makeHTTPRequest(url_mahasiswa_details, "GET",
param);
Log.d("Single Mahasiswa Details", json.toString());

success = json.getInt(TAG_SUCCESS);
if(success == 1)
{
JSONArray siswaOBJB = json.getJSONArray(TAG_MAHASISWA);

JSONObject siswa = siswaOBJB.getJSONObject(0);


editENPM = (EditText) findViewById(R.id.editEDITNPM);
editENAMA = (EditText) findViewById(R.id.editEDITNAMA);
editEKELAS = (EditText) findViewById(R.id.editEDITKELAS);
editEALAMAT = (EditText) findViewById(R.id.editEDITALAMAT);

editENPM.setText(siswa.getString(TAG_NPM));
editENAMA.setText(siswa.getString(TAG_NAMA));
editEKELAS.setText(siswa.getString(TAG_KELAS));
editEALAMAT.setText(siswa.getString(TAG_ALAMAT));
}
else
{

}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}).start();
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
class UpdateSiswa extends AsyncTask<String, String, String>
{

Tutorial Android Mysql | Muharir.,M.Kom


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
super.onPreExecute();
pDialog = new ProgressDialog(EditDataActivity.this);
pDialog.setMessage("Mengambil Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String npm = editENPM.getText().toString();
String nama = editENAMA.getText().toString();
String kelas = editEKELAS.getText().toString();
String alamat = editEALAMAT.getText().toString();

List<NameValuePair> param = new ArrayList<NameValuePair>();

param.add(new BasicNameValuePair(TAG_ID, id));


param.add(new BasicNameValuePair(TAG_NPM, npm));
param.add(new BasicNameValuePair(TAG_NAMA, nama));
param.add(new BasicNameValuePair(TAG_KELAS, kelas));
param.add(new BasicNameValuePair(TAG_ALAMAT, alamat));
JSONObject json = jsonParser.makeHTTPRequest(url_update_mahasiswa, "POST", param);
try
{
int success = json.getInt(TAG_SUCCESS);
if(success ==1)
{
Intent i = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(i);
}
else
{

}
}
catch(JSONException e)

Tutorial Android Mysql | Muharir.,M.Kom


{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
class DeleteSiswa extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(EditDataActivity.this);
pDialog.setMessage("Mengambil Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
int success;
try
{
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id", id));

JSONObject json = jsonParser.makeHTTPRequest(url_delete_mahasiswa, "POST", param);

Log.d("Hapus Data", json.toString());

success = json.getInt(TAG_SUCCESS);
if(success == 1)
{
Intent i = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(i);

Tutorial Android Mysql | Muharir.,M.Kom


}
else
{

}
}
catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
}

Terakhir pada AndroidManifest.xml tambahkan permission internet seperti berikut :

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


Sehingga menjadi seperti berikut :

Tutorial Android Mysql | Muharir.,M.Kom


Tampilan Akhir Aplikasi :

Selesai

Tutorial Android Mysql | Muharir.,M.Kom


DRM Software Review

Anda mungkin juga menyukai