最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android App端與PHP Web端的簡單數(shù)據(jù)交互實(shí)現(xiàn)示例

 更新時間:2017年10月23日 15:04:09   作者:uknow  
本篇文章主要介紹了Android App端與PHP Web端的簡單數(shù)據(jù)交互實(shí)現(xiàn)示例,詳細(xì)的介紹了交互的代碼,非常具有實(shí)用價值,有興趣的可以了解一下

前言

由于學(xué)??萍剂㈨?xiàng)的項(xiàng)目需要實(shí)現(xiàn)Android App端與PHP Web端的簡單數(shù)據(jù)交互的實(shí)現(xiàn),當(dāng)前場景是Web端使用的是MySql數(shù)據(jù)庫,Apache服務(wù)器和PHP語言編寫的。數(shù)據(jù)交互的簡單理解就是Android能向服務(wù)端進(jìn)行數(shù)據(jù)獲取,同時也能進(jìn)行數(shù)據(jù)提交。

實(shí)現(xiàn)流程

流程說明

  1. Andorid Server端對MySql數(shù)據(jù)庫進(jìn)行簡單的查詢操作,并將查詢數(shù)據(jù)結(jié)果轉(zhuǎn)換為Json格式提供給Andorid利用OKhttp讀取再解析Json展示到APP上;同時Andorid端利用OKhttp提交給Andorid Server端,由Server端對MySql數(shù)據(jù)庫對提交數(shù)據(jù)的添加。
  2. Apache Server端通過解析PHP源代碼,對MySql數(shù)據(jù)庫的增刪查改顯示在WebSite。

具體實(shí)現(xiàn)

Andorid Server

獲取數(shù)據(jù)

get_all_found_items.php

<?php 
header('Content-Type:text/html;charset=utf-8');/*設(shè)置php編碼為utf-8*/
/* 
 * Following code will list all the items 
 */ 
  
// array for JSON response 
$response = array(); 
  
// include db connect class 
require_once __DIR__ . '/db_connect.php'; 
  
// connecting to db 
$db = new DB_CONNECT(); 
  
// get all items from items table 
$result = mysql_query("SELECT *FROM items WHERE type='1'") or die(mysql_error()); 
// check for empty result 
if (mysql_num_rows($result) > 0) { 
  // looping through all results 
  // items node 
  $response["items"] = array(); 
  
  while ($row = mysql_fetch_array($result)) { 
    // temp user array 
    $items = array(); 
    $items["what"] = $row["what"]; 
    $items["when"] = $row["when"]; 
    $items["where"] = $row["where"]; 
    $items["detail"] = $row["detail"];
    $items["posttime"] = $row["posttime"];  
 $resultcontcat = mysql_query("SELECT *FROM guests") or die(mysql_error()); 
 while ($row1 = mysql_fetch_array($resultcontcat)) { 
  if ($row1["id"] == $row["gid"]){
  $items["contact"] = $row1["contact"];
  }
  }
    // push single items into final response array 
    array_push($response["items"], $items); 
  } 
  // success 
  $response["success"] = 1; 
  
  // echoing JSON response 
  echo json_encode($response,JSON_UNESCAPED_UNICODE); 
} else { 
  // no items found 
  $response["success"] = 0; 
  $response["message"] = "No items found"; 
  
  // echo JSON 
  echo json_encode($response,JSON_UNESCAPED_UNICODE); 
} 
?>

如以上PHP代碼可知通過require_once()函數(shù)包含db_connect.php文件,執(zhí)行數(shù)據(jù)庫配置文件。定義數(shù)組$response接收查詢的數(shù)據(jù)結(jié)果,通過判斷不同的情況賦值$response[“success”],并返回到Web頁面顯示

PHP文件執(zhí)行結(jié)果

JSON

 {
  "items": [
    {
      "what": "手表",
      "when": "2017-10-21 00:00:00",
      "where": "北區(qū)宿舍樓#504",
      "detail": "白色的手表,XX品牌",
      "posttime": "2017-10-21 13:03:09",
      "contact": "138123456"
    },
    {
      "what": "手機(jī)",
      "when": "2017-10-04 00:00:00",
      "where": "北區(qū)商店#111",
      "detail": "iphone6s,土豪金",
      "posttime": "2017-10-21 13:03:46",
      "contact": "137123456"
    },
    {
      "what": "電腦",
      "when": "2017-10-21 14:39:54",
      "where": "圖書館#203",
      "detail": "聯(lián)想品牌筆記本",
      "posttime": "2017-10-21 17:08:14",
      "contact": "5670001"
    },
    {
      "what": "細(xì)說PHP",
      "when": "2017-09-21 13:03:46",
      "where": "南館#403",
      "detail": "黑色封面,第二版《細(xì)說PHP》",
      "posttime": "2017-10-21 17:36:53",
      "contact": "63513641"
    }
  ],
  "success": 1
}

提交數(shù)據(jù)

create_found_items.php

<?php 
header('Content-Type:text/html;charset=utf-8');/*設(shè)置php編碼為utf-8*/  
/* 
 * Following code will create a new product row 
 * All product details are read from HTTP GET Request 
 */ 
  
// array for JSON response 
$response = array(); 
  
// check for required fields 
if (isset($_GET['what']) && isset($_GET['when']) && isset($_GET['where']) && isset($_GET['detail'])&& isset($_GET['contact'])) { 
  
  $what = $_GET['what']; 
  $when = $_GET['when']; 
  $where = $_GET['where']; 
  $detail = $_GET['detail']; 
  $contact = $_GET['contact']; 
 
  // include db connect class 
  require_once __DIR__ . '/db_connect.php'; 
  
  // connecting to db 
  $db = new DB_CONNECT(); 
  
  // mysql inserting a new row 
 $result2 = mysql_query("INSERT INTO guests(contact) VALUES('$contact')"); 
 $gidresult = mysql_query("SELECT id FROM `guests` WHERE contact='$contact'"); 
 while ($row = mysql_fetch_array($gidresult)) { 
  $gid=$row['id'];
 }
  $result1 = mysql_query("INSERT INTO items(`what`, `when`, `where`, `type` ,`gid`, `detail`) VALUES('$what', '$when', '$where', '1', '$gid', '$detail')");  
  
  // check if row inserted or not 
  if ($result1 && $result2) { 
    // successfully inserted into database 
    $response["success"] = 1; 
    $response["message"] = "Items successfully created."; 
  
    // echoing JSON response 
  echo json_encode($response,JSON_UNESCAPED_UNICODE);  
  } else { 
    // failed to insert row 
    $response["success"] = 0; 
    $response["message"] = "Oops! An error occurred."; 
  
    // echoing JSON response 
  echo json_encode($response,JSON_UNESCAPED_UNICODE);  
  } 
} else { 
  // required field is missing 
  $response["success"] = 0; 
  $response["message"] = "Required field(s) is missing"; 
  
  // echoing JSON response 
  echo json_encode($response,JSON_UNESCAPED_UNICODE);  
} 
?>

判斷GET請求的參數(shù)是否都存在,把獲取的GET請求參數(shù)作為數(shù)據(jù)INSERT TO MySQL數(shù)據(jù)庫。判斷INSERT執(zhí)行過程賦值$response[“success”]對應(yīng)相應(yīng)的$response[“message”],顯示在Web頁面。

執(zhí)行結(jié)果

Andorid

獲取數(shù)據(jù)

核心代碼 queryLosts()函數(shù)

private void queryLosts() {
 losts.clear();
 new Thread(new Runnable() {
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  
     OkHttpClient okHttpClient = new OkHttpClient();
     String url = "http://webSite/androidapi/get_all_lost_items.php";
     Request request = new Request.Builder()
         .url(url)
         .build();
     Call call = okHttpClient.newCall(request);
     try {
       Response response = call.execute();
       String res = response.body().string();
       if (res != null && !res.trim().equals("")){
         JSONObject jsonObject = new JSONObject(res);
         if (jsonObject.getInt("success") == 1){
           JSONArray jsonArray = jsonObject.getJSONArray("items");
           for (int i = jsonArray.length() - 1;i >= 0;i--){
             JSONObject item = jsonArray.getJSONObject(i);
             String what = null;
             try {
               what = item.getString("what");
             }catch (Exception e){
             }
             String when = null;
             try{
               when = item.getString("when");
             }catch (Exception e){
             }
             String where = null;
             try{
               where = item.getString("where");
             }catch (Exception e){
             }
             String detail = null;
             try {
               detail = item.getString("detail");
             }catch (Exception e){
             }
             String contact = null;
             try {
               contact = item.getString("contact");
             }catch (Exception e){
             }
             Lost lost = new Lost();
             lost.setTitle(what);
             String des = "地點(diǎn):" + (where == null?"":where) +"   "+"時間:" + (when == null?"":when)+"\r" + "   "+"描述:" + (detail == null?"":detail);
             lost.setDescribe(des);
             lost.setPhone(contact == null?"":contact);
             losts.add(lost);
           }
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
       showErrorView(0);
     }
     if (losts == null || losts.size() == 0) {
     handler.sendEmptyMessage(1);
       return;
     }
     if (losts.size() > 0){
      handler.sendEmptyMessage(2);
     }
 }
 }).start();

利用Android網(wǎng)絡(luò)框架OKhttp,OKhttp一個處理網(wǎng)絡(luò)請求的開源項(xiàng)目,是安卓端最火熱的輕量級框架.請求接口url地址,獲取Json數(shù)據(jù)利用JSONObject對Json數(shù)據(jù)進(jìn)行解析。

提交數(shù)據(jù)

核心代碼 addLost()函數(shù)

public Handler handler = new Handler(){
 public void handleMessage(android.os.Message msg) {
 switch(msg.what){
  case 1:
  Toast.makeText(this,"提交成功",Toast.LENGTH_LONG).show();
  break;
  case 2:
  Toast.makeText(this,"提交失敗",Toast.LENGTH_LONG).show();
  break;
 }
 }
};
private void addLost(){
 OkHttpClient okHttpClient = new OkHttpClient();
 String url ="http://website/androidapi/create_lost_items.php?what="+title+"&when="+time+"&where="+place+"&detail="+describe+"&contact="+photo+"";
 Request request = new Request.Builder()
  .url(url)
  .build();
 
 try{
 Response response = okHttpClient.newCall(request).execute();
 res = response.body().string();
 handler.sendEmptyMessage(1);
 }catch (Exception e)
 {
 e.printStackTrace();
 handler.sendEmptyMessage(2);
 }
}

同樣利用Okhttp,GET方式提交參數(shù),try-catch獲取異常,通過返回值給出一定的提交結(jié)果提示。

代碼測試

數(shù)據(jù)同步

Web端

Andorid端

數(shù)據(jù)提交

提交結(jié)果

結(jié)語

以上過程基本實(shí)現(xiàn),項(xiàng)目基本上可以交差了。這個項(xiàng)目PHP部分主要是由自己在弄,也是邊學(xué)邊做。Android方面是另外一個同學(xué)主要負(fù)責(zé),期間也求助過我實(shí)習(xí)時結(jié)交的朋友幫助。感謝所有付出與幫助的人。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Android 對Map按key和value分別排序的實(shí)例

    Android 對Map按key和value分別排序的實(shí)例

    下面小編就為大家?guī)硪黄狝ndroid 對Map按key和value分別排序的實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-12-12
  • Android仿微信多人音視頻通話界面

    Android仿微信多人音視頻通話界面

    這篇文章主要為大家詳細(xì)介紹了Android仿微信多人音視頻通話界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • Android 操作系統(tǒng)獲取Root權(quán)限 原理詳細(xì)解析

    Android 操作系統(tǒng)獲取Root權(quán)限 原理詳細(xì)解析

    許多機(jī)友新購來的Android機(jī)器沒有破解過Root權(quán)限,無法使用一些需要高權(quán)限的軟件,以及進(jìn)行一些高權(quán)限的操作,其實(shí)破解手機(jī)Root權(quán)限是比較簡單及安全的,破解Root權(quán)限的原理就是在手機(jī)的/system/bin/或/system/xbin/目錄下放置一個可執(zhí)行文件“su”
    2013-10-10
  • 詳解Android 全局彈出對話框SYSTEM_ALERT_WINDOW權(quán)限

    詳解Android 全局彈出對話框SYSTEM_ALERT_WINDOW權(quán)限

    本篇文章主要介紹了詳解Android 全局彈出對話框SYSTEM_ALERT_WINDOW權(quán)限,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • AndroidStudio中AVD虛擬機(jī)設(shè)備空間不足調(diào)試過程出現(xiàn)的黑屏問題及解決方案

    AndroidStudio中AVD虛擬機(jī)設(shè)備空間不足調(diào)試過程出現(xiàn)的黑屏問題及解決方案

    這篇文章主要介紹了解決AndroidStudio中AVD虛擬機(jī)設(shè)備空間不足調(diào)試過程出現(xiàn)的黑屏問題,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • Android單選按鈕RadioButton的使用詳解

    Android單選按鈕RadioButton的使用詳解

    今天小編就為大家分享一篇關(guān)于Android單選按鈕RadioButton的使用詳解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • Android貝塞爾曲線實(shí)現(xiàn)手指軌跡

    Android貝塞爾曲線實(shí)現(xiàn)手指軌跡

    這篇文章主要為大家詳細(xì)介紹了Android貝塞爾曲線實(shí)現(xiàn)手指軌跡效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • 基于Android實(shí)現(xiàn)系統(tǒng)重啟reboot功能

    基于Android實(shí)現(xiàn)系統(tǒng)重啟reboot功能

    在某些特殊場景下(如設(shè)備管理、安全監(jiān)控、工控系統(tǒng)等),開發(fā)者可能需要實(shí)現(xiàn)系統(tǒng)重啟功能,本文給大家介紹了如何基于Android實(shí)現(xiàn)系統(tǒng)重啟reboot功能,需要的朋友可以參考下
    2025-04-04
  • 詳解OkSocket與Android的簡單使用

    詳解OkSocket與Android的簡單使用

    本篇文章主要介紹了詳解OkSocket與Android的簡單使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • GreenDao 3.2.0 的基本使用

    GreenDao 3.2.0 的基本使用

    本文主要對GreenDao 3.2.0 的基本使用進(jìn)行詳細(xì)介紹。具有一定的參考價值,下面跟著小編一起來看下吧
    2017-01-01

最新評論

桂林市| 奇台县| 西华县| 平远县| 吉木萨尔县| 嘉定区| 榆林市| 伊宁县| 蓝田县| 精河县| 靖边县| 仪征市| 北京市| 奎屯市| 华蓥市| 双峰县| 泸水县| 禹州市| 河源市| 五寨县| 桑日县| 周口市| 昌乐县| 宝坻区| 泰安市| 云霄县| 红河县| 长治县| 永福县| 瓦房店市| 黄骅市| 南澳县| 西乌珠穆沁旗| 武强县| 泰兴市| 阆中市| 白银市| 湖口县| 潼关县| 富裕县| 广东省|