Mengkoneksikan Aplikasi Android Dengan Database MySQL Menggunakan
Mengkoneksikan Aplikasi Android Dengan Database MySQL Menggunakan
Assalamu’alaikum Wr. Wb
Happy Monday !!
Siang ini saya akan berbagi tentang cara mengkoneksikan aplikasi android dengan
database MySQL menggunakan JSON.
JSON singkatan dari JavaScript Object Notation. Yaitu sebuah format data standar
berbasis text yang mudah dibaca dan dibuat, dan kegunaan nya untukdata
interchange atau pertukaran data antara sebuah server dengan aplikasi web. Format
JSON adalah merupakan alternatif dari format data XML.
JSON diturunkan dari bahasa pemrograman JavaScript, tujuan dibuat JSON adalah
untuk membuat struktur data sederhana yang bisa menampung array dan
objek. Walaupun demikian, hubungan JSON dengan JavaScript adalah independen
(untuk menggunakan JSON tidak harus menggunakan JavasScript). Sampai saat ini
hampir semua bahasa pemrograman sudah menyediakan fungsi untuk
melakukan parsing format data JSON. Contohnya pada PHP adalah fungsi
json_encode() dan json_decode().
define('DB_USER', "root");
define('DB_PASSWORD', "");
define('DB_DATABASE', "motorcycle_db");
define('DB_SERVER', "localhost");
?>
gdg
db_connect.php
<?php
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
/**
*/
function connect() {
// Selecing database
return $con;
}
function close() {
// closing db connection
mysql_close();
?>
get_all.php
<?php
/*
*/
$response = array();
// connecting to db
if (mysql_num_rows($result) > 0) {
// products node
$response["products"] = array();
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
$product["brand"] = $row["brand"];
array_push($response["products"], $product);
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
echo json_encode($response);
?>
get_motorcycle_details.php
<?php
$response = array();
// connecting to db
$id = $_GET['id'];
//$id = 1;
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["id"] = $result["id"];
$product["name"] = $result["name"];
$product["brand"] = $result["brand"];
// success
$response["success"] = 1;
// user node
$response["products"] = array();
array_push($response["products"], $product);
} else {
// no product found
$response["success"] = 0;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
?>
insert_motorcycle.php
<?php
$response = array();
$name = $_POST['name'];
$brand = $_POST['brand'];
// connecting to db
if ($result) {
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
?>
delete_motorcycle.php
<?php
/*
*/
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// connecting to db
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
?>
update_motorcycle.php
<?php
/*
*/
$response = array();
$id = $_POST['id'];
$name = $_POST['name'];
$brand = $_POST['brand'];
// connecting to db
if ($result) {
// successfully updated
$response["success"] = 1;
echo json_encode($response);
} else {
} else {
$response["success"] = 0;
echo json_encode($response);
?>
get_motorcycle_details.php
<?php
$response = array();
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["id"])) {
$id = $_GET['id'];
//$id = 1;
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["id"] = $result["id"];
$product["name"] = $result["name"];
$product["brand"] = $result["brand"];
// success
$response["success"] = 1;
// user node
$response["products"] = array();
array_push($response["products"], $product);
} else {
// no product found
$response["success"] = 0;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#95959c">
<Button android:id="@+id/bt_motorcycleList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Motorcycle List"
android:textColor="#FFFFFF"
android:layout_marginTop="25dip"
android:background="#000000"/>
<Button android:id="@+id/bt_insertMotorcycle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Motorcycle"
android:textColor="#FFFFFF"
android:layout_marginTop="25dip"
android:background="#000000"/>
</LinearLayout>
all_motorcycles.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
add_motorcycles.xml
<?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" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Motorcycle Name"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<EditText android:id="@+id/inputName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Brand"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<EditText android:id="@+id/inputBrand"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<Button android:id="@+id/btnAddMotorcycle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Motorcycle"/>
</LinearLayout>
edit_motorcycles.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Motorcycle Name"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<EditText android:id="@+id/inputName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- Price Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Brand"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<EditText android:id="@+id/inputBrand"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="numberDecimal"/>
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="@+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save Changes"
android:layout_weight="1"/>
<Button android:id="@+id/btnDelete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dip"
android:textStyle="bold"
android:text="Name :"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:text="Motorcycle Name"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/label_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dip"
android:textStyle="bold"
android:text="Brand :"/>
<TextView
android:id="@+id/brand"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:text="Brand Name"/>
</LinearLayout>
</LinearLayout>
Button btnMotorcycleList;
Button btnAddMotorcycle;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMotorcycleList.setOnClickListener(new View.OnClickListener() {
@Override
startActivity(i);
}
});
btnAddMotorcycle.setOnClickListener(new View.OnClickListener() {
@Override
startActivity(i);
}
});
}
}
JSONParser.java
try {
if(method == "POST"){
httpPost.setEntity(new UrlEncodedFormEntity(params));
is = httpEntity.getContent();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
try {
sb.append(line + "\n");
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
} catch (JSONException e) {
return jObj;
AllMotorcycleView.java
// products JSONArray
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.all_motorcycles);
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
in.putExtra(ID, id_motorcycle);
startActivityForResult(in, 100);
});
@Override
if (resultCode == 100) {
finish();
startActivity(intent);
/**
* */
/**
* */
@Override
super.onPreExecute();
pDialog = new ProgressDialog(AllMotorcycleView.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
// Building Parameters
try {
if (success == 1) {
products = json.getJSONArray(PRODUCTS);
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(ID);
map.put(ID, id);
map.put(NAME, name);
map.put(BRAND, brand);
productsList.add(map);
} else {
// no products found
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
return null;
/**
* **/
pDialog.dismiss();
runOnUiThread(new Runnable() {
// updating listview
setListAdapter(adapter);
});
}
}
EditMotorcycle.java
EditText txtName;
EditText txtBrand;
Button btnSave;
Button btnDelete;
String id;
// Progress Dialog
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_motorcycle);
// save button
Intent i = getIntent();
id = i.getStringExtra(ID);
new GetProductDetails().execute();
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
new SaveProductDetails().execute();
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
new DeleteProduct().execute();
});
@Override
super.onPreExecute();
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
int success;
try {
Log.d("ID", id);
success = json.getInt(SUCCESS);
if (success == 1) {
// Edit Text
txtName.setText(product.getString(NAME));
txtBrand.setText(product.getString(BRAND));
}else{
} catch (JSONException e) {
e.printStackTrace();
return null;
/**
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
/**
* */
/**
* */
@Override
super.onPreExecute();
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
// Building Parameters
try {
// successfully updated
Intent i = getIntent();
setResult(100, i);
finish();
} else {
} catch (JSONException e) {
e.printStackTrace();
return null;
pDialog.dismiss();
}
/*****************************************************************
* */
/**
* */
@Override
super.onPreExecute();
pDialog.setMessage("Deleting Motorcycle...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
/**
* Deleting product
* */
try {
// Building Parameters
success = json.getInt(SUCCESS);
if (success == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
return null;
/**
* **/
pDialog.dismiss();
ConstantValue.java
public final static String BASE_URL = "http://" + HOST_NAME + "/" + MAIN_FOLDER + "/";
public final static String DISPLAY_ALL = BASE_URL + "get_all.php";
InsertMotorcycleView.java
// Progress Dialog
EditText inputName;
EditText inputBrand;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_motorcycle);
// Edit Text
// Create button
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
new AddMotorcycle().execute();
});
}
/**
* */
/**
* */
@Override
super.onPreExecute();
pDialog.setMessage("Add motorcycle..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
/**
* Creating product
* */
// Building Parameters
try {
if (success == 1) {
finish();
} else {
} catch (JSONException e) {
e.printStackTrace();
return null;
/**
* **/
pDialog.dismiss();
}
Bukalah file AndroidMenifest.xml, dan tambahkan potongan program
ini diluar tag application.
<!-- Internet Permissions -->
<activity
android:name=".AllMotorcycleView"
</activity>
<activity
android:name=".InsertMotorcycleView"
</activity>
<activity
android:name=".EditMotorcycleView"
</activity>