[Android Studio] Android Native App 에서 mysql , php 연결 : PHP MySQL REST API for Android

PHP MySQL REST API for Android

php-mysql-rest-api-for-android-bundle.zip

PHP REST API backed up with a MySQL database is a very common schematic of an Enterprise mobile application. When the scenario requires data to be stored in a centralized manner, then this architecture should be used.Otherwise, the local database in the mobile can be used for the storage and retrieval of information.

In this tutorial, we are creating a PHP RESTful service to read data from a (MySQL) database table. Also, I am providing an example Android project code for invoking this RESTful service.

In a previous tutorial, we have seen then basics about PHP RESTful services. I strongly recommend you to go through it before continuing this tutorial.

In this example, we are calling the PHP REST API from an android application. In the server side, the API service reads data from the database and sends the response in JSON format. After receiving the response, the Android application displays the row of items in a ListView by parsing the JSON data.

If you want to see how to handle JSON data with PHP with detailed notes and examples, then the linked article will be a perfect tutorial on this.

PHP REST API flow

PHP REST API that Reads MySQL Records

We have a database table containing the list of mobile phone model names. Our REST API fetches the list of mobile names from the database and sends the response in JSON. This REST API contains three parts. These are, the REST controller, service class, and the DAO.

RestController.php

The REST call lands on this controller. It calls the service to prepare a response.

<?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 invokes DAO function to read data from the database table. Since our application requests JSON type data, the service class prepares the response in JSON format.

<?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 Access

In this example, we are creating a simple Android app for accessing MySQL data using a REST API in PHP. We are having a ListView element in the MainActivity.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

We are creating a ListView Adapter to add the list of items returned as the API response. Then we set this adapter to the ListView element to display MySQL data rows.

On launching the MainActivity, we invoke the AsyncTask to access PHP MySQL REST API. We use “HTTPConnectionRequest” class to set params and send the request to the API. The following code shows the MainActivity class.

package com.phppot.code.phprestapp;

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
}

and the XML content files are,

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" />

Output:

download

[출처] https://phppot.com/php/php-mysql-rest-api-for-android/

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
113 [android studio] 안드로이드 아이콘이 2개 생성될 때 졸리운_곰 2023.03.21 81
112 [android studio] Convert Any Website to Android App using Android Studio file 졸리운_곰 2023.03.18 63
111 [android studio] How to Convert Any Website to Android App in Android Studio? file 졸리운_곰 2023.03.18 80
110 [phonegap][cordova] [안드로이드] 코도바 앱(App) 개발 환경 세팅 file 졸리운_곰 2023.02.05 81
109 [android studio] 에러 해결: android gradle plugin requires java 11 to run. you are currently using java 1.8. file 졸리운_곰 2022.11.17 64
108 [android sdk] 안드로이드에서 JWT 사용하기 졸리운_곰 2022.07.15 107
» [Android Studio] Android Native App 에서 mysql , php 연결 : PHP MySQL REST API for Android file 졸리운_곰 2021.12.02 153
106 Android PHP MySQL 예제 - 데이터베이스에서 데이터를 JSON 형식으로 가져오기 file 졸리운_곰 2021.07.24 276
105 Android PHP MySQL 예제 - 데이터베이스 질의(query) 결과 출력하기 file 졸리운_곰 2021.07.24 616
104 [android] 안드로이드에서 mysql 데이터베이스 입력, 접속 / Android PHP MySQL 예제 - 데이터베이스에 데이터 입력하기 file 졸리운_곰 2021.07.24 173
103 Android 에서 Opencv 설치하고 간단한 예제 실행해보기!! file 졸리운_곰 2020.10.31 438
102 안드로이드 나인 패치(9-Patch) 이미지 버튼. (Android Nine-Patch Image Button) file 졸리운_곰 2020.10.10 202
101 나인패치(Nine Patch) 이미지란? file 졸리운_곰 2020.10.10 129
100 Python으로 안드로이드 앱 만들기 졸리운_곰 2020.09.30 928
99 [Android] Fragment 를 이용한 탭 만들기 file 졸리운_곰 2020.09.19 115
98 빠르게배우는 안드로이드 Fragment-4(Fragment간 에 데이터전달) file 졸리운_곰 2020.09.19 85
97 빠르게배우는 안드로이드 Fragment-3(Fragment기초 실습) file 졸리운_곰 2020.09.19 114
96 빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경) 졸리운_곰 2020.09.19 103
95 빠르게배우는 안드로이드 Fragment -1 (배경) file 졸리운_곰 2020.09.19 127
94 안드로이드 스튜디오 - 새로 생성한 Activity Class를 쉽게 Manifest에 등록하기. file 졸리운_곰 2020.08.08 129
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED