Nama = Muhammad Rois
Nim = 18.01.53.2048
Disini saya sudah memiliki tabel database yang berisi daftar nama model ponsel. REST API akan mengambil daftar nama seluler dari database dan mengirimkan respons di JSON. REST API ini terdiri dari tiga bagian. Rest Controller, Service Class, dan DAO.
RestController.php
Pengontrol berguna untuk memanggil layanan untuk menyiapkan tanggapan.
<?php
require_once("MobileRestHandler.php");
$view = "";
if(isset($_GET["view"]))
$view = $_GET["view"];
/*
controls the RESTful services
URL mapping
*/
switch($view){
case "all":
// to handle REST Url /mobile/list/
$mobileRestHandler = new MobileRestHandler();
$mobileRestHandler->getAllMobiles();
break;
case "" :
//404 - not found;
break;
}
?>
MobileRestHanler.php
Service class memanggil fungsi DAO untuk membaca data dari tabel database. Karena aplikasi ini meminta data jenis JSON, maka service class menyiapkan respons dalam format JSON.
<?php
require_once("SimpleRest.php");
require_once("Mobile.php");
class MobileRestHandler extends SimpleRest {
function getAllMobiles() {
$mobile = new Mobile();
$rawData = $mobile->getAllMobile();
if(empty($rawData)) {
$statusCode = 404;
$rawData = array('error' => 'No mobiles found!');
} else {
$statusCode = 200;
}
$requestContentType = 'application/json';//$_POST['HTTP_ACCEPT'];
$this ->setHttpHeaders($requestContentType, $statusCode);
$result["output"] = $rawData;
if(strpos($requestContentType,'application/json') !== false){
$response = $this->encodeJson($result);
echo $response;
}
}
public function encodeJson($responseData) {
$jsonResponse = json_encode($responseData);
return $jsonResponse;
}
}
?>
Mobile.php
<?php
require_once("dbcontroller.php");
/*
A domain Class to demonstrate RESTful web services
*/
Class Mobile {
private $mobiles = array();
/*
you should hookup the DAO here
*/
public function getAllMobile(){
$query = "SELECT * FROM tbl_mobile";
$dbcontroller = new DBController();
$this->mobiles = $dbcontroller->executeSelectQuery($query);
return $this->mobiles;
}
}
?>
Android App – PHP REST API
Dalam contoh ini, saya membuat aplikasi Android sederhana untuk mengakses data MySQL menggunakan REST API di PHP. Saya memiliki elemen ListView di MainActivity Android. Saya membuat Adaptor ListView untuk menambahkan daftar item yang dikembalikan sebagai respons API. Kemudian saya mengatur adaptor ini ke elemen ListView untuk menampilkan baris data MySQL.
Saya memanggil AsyncTask untuk mengakses PHP MySQL REST API. Saya menggunakan kelas "HTTPConnectionRequest" untuk mengatur params dan mengirim permintaan ke API.
Berikut Kode MainActivity.java
package com.tugas;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String apiPath = "http://10.0.2.2/phpsamples/php-mysql-rest-api-for-android/mobile/list/";
private ProgressDialog processDialog;
private JSONArray restulJsonArray;
private int success = 0;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mobile_name_list);
new ServiceStubAsyncTask(this, this).execute();
}
private class ServiceStubAsyncTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
private Activity mActivity;
String response = "";
HashMap<String, String> postDataParams;
public ServiceStubAsyncTask(Context context, Activity activity) {
mContext = context;
mActivity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
processDialog = new ProgressDialog(mContext);
processDialog.setMessage("Please Wait ...");
processDialog.setCancelable(false);
processDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
postDataParams = new HashMap<String, String>();
postDataParams.put("HTTP_ACCEPT", "application/json");
HttpConnectionService service = new HttpConnectionService();
response = service.sendRequest(apiPath, postDataParams);
try {
success = 1;
JSONObject resultJsonObject = new JSONObject(response);
restulJsonArray = resultJsonObject.getJSONArray("output");
} catch (JSONException e) {
success = 0;
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (processDialog.isShowing()) {
processDialog.dismiss();
}
if (success == 1) {
if (null != restulJsonArray) {
ArrayAdapter listViewAdapter = new ArrayAdapter<String>(mContext, R.layout.mobile_name_listview);
for (int i = 0; i < restulJsonArray.length(); i++) {
try {
JSONObject jsonObject = restulJsonArray.getJSONObject(i);
listViewAdapter.add(jsonObject.get("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
listView.setAdapter(listViewAdapter);
}
}
}
}//end of async task
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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.phppot.code.phprestapp.MainActivity"
android:background="#000000"
android:padding="0dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mobile_name_list"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_marginBottom="124dp"
android:layout_alignParentTop="true"
android:divider="#5e5e5f"
android:dividerHeight="1dp"
android:drawSelectorOnTop="true"
android:layout_margin="0dp"
android:padding="0dp" />
</RelativeLayout>
mobile_name_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/list_item"
android:textColor="#FFFFFF"
android:background="#000"
android:textSize="18dp"
android:paddingTop="20dp"
android:paddingBottom="20dp" />
Komentar
Posting Komentar