如何使用JSON連接Android和PHP Mysql數據庫

轉自:http://blog.csdn.net/welovesunflower/article/details/7776438


我們先來看一個簡單的Android app例子(這裏是一個商品存貨清單項目),在Android程序中,我們可以訪問(call)PHP腳本來執行簡單的CRUD操作(創建,讀取,更新,刪除)。爲了使你對它的體系結構有一個大概的瞭解,這裏先說一下它是怎麼工作的。首先你的Android項目訪問(call)PHP腳本來執行一條數據操作,我們稱它爲“創建”。然後PHP腳本連接MySQL數據庫來執行這個操作。這樣,數據從Android程序流向PHP腳本,最終存儲在MySQL數據庫中。

好了,讓我們來深入的看一下。

請注意:這裏提供的代碼只是爲了使你能簡單的連接Android項目和PHP,MySQL。你不能把它作爲一個標準或者安全編程實踐。在生產環境中,理想情況下你需要避免使用任何可能造成潛在注入漏洞的代碼(比如MYSQL注入)。MYSQL注入是一個很大的話題,不可能用單獨的一篇文章來說清楚,並且它也不在本文討論的範圍內,所以本文不以討論。

1. 什麼是WAMP Server

WAMP是Windows,Apache,MySQL和PHP,Perl,Python的簡稱。WAMP是一個一鍵安裝的軟件,它爲開發PHP,MySQL Web應用程序提供一個環境。安裝這款軟件你相當於安裝了Apache,MySQL和PHP。或者,你也可以使用XAMP


2. 安裝和使用WAMP Server

你可以從http://www.wampserver.com/en/下載WAMP,安裝完成之後,可以從開始->所有程序->WampServer->StartWampServer運行該程序。

在瀏覽器中輸入http://localhost/來測試你的服務器是否安裝成功。同樣的,也可以打開http://localhost/phpmyadmin來檢驗phpmyadmin是否安裝成功。

3. 創建和運行PHP項目

現在,你已經有一個能開發PHP和MYSQL項目的環境了。打開安裝WAMP Server的文件夾(在我的電腦中,是C:\wamp\),打開www文件夾,爲你的項目創建一個新的文件夾。你必須把項目中所有的文件放到這個文件夾中。

新建一個名爲android_connect的文件夾,並新建一個php文件,命名爲test.php,嘗試輸入一些簡單的php代碼(如下所示)。輸入下面的代碼後,打開http://localhost/android_connect/test.php,你會在瀏覽器中看到“Welcome,I am connecting Android to PHP,MySQL”(如果沒有正確輸入,請檢查WAMP配置是否正確)

test.php

  1. <?php   
  2. echo"Welcome, I am connecting Android to PHP, MySQL";   
  3. ?>  
4. 創建MySQL數據庫和表

在本教程中,我創建了一個簡單的只有一張表的數據庫。我會用這個表來執行一些示例操作。現在,請在瀏覽器中輸入http://localhost/phpmyadmin/,並打開phpmyadmin。你可以用PhpMyAdmin工具創建數據庫和表。

創建數據庫和表:數據庫名:androidhive,表:product

  1. CREATE TABLE products(  
  2. pid int(11) primary key auto_increment,  
  3. name varchar(100) not null,  
  4. price decimal(10,2) not null,  
  5. description text,  
  6. created_at timestamp default now(),  
  7. updated_at timestamp  
  8. );  
5. 用PHP連接MySQL數據庫

現在,真正的服務器端編程開始了。新建一個PHP類來連接MYSQL數據庫。這個類的主要功能是打開數據庫連接和在不需要時關閉數據庫連接。

新建兩個文件db_config.php,db_connect.php

db_config.php--------存儲數據庫連接變量
db_connect.php-------連接數據庫的類文件

db_config.php

  1. <?php  
  2.    
  3. /* 
  4.  * All database connection variables 
  5.  */  
  6.    
  7. define('DB_USER'"root"); // db user  
  8. define('DB_PASSWORD'""); // db password (mention your db password here)  
  9. define('DB_DATABASE'"androidhive"); // database name  
  10. define('DB_SERVER'"localhost"); // db server  
  11. ?>  

這裏的DB_USER  DB_PASSWORD要換成自己數據庫對應的用戶名、密碼

db_connect.php

  1.  <?php  
  2.    
  3. /** 
  4.  * A class file to connect to database 
  5.  */  
  6. class DB_CONNECT {  
  7.    
  8.     // constructor  
  9.     function __construct() {  
  10.         // connecting to database  
  11.         $this->connect();  
  12.     }  
  13.    
  14.     // destructor  
  15.     function __destruct() {  
  16.         // closing db connection  
  17.         $this->close();  
  18.     }  
  19.    
  20.     /** 
  21.      * Function to connect with database 
  22.      */  
  23.     function connect() {  
  24.         // import database connection variables  
  25.         require_once __DIR__ . '/db_config.php';  
  26.    
  27.         // Connecting to mysql database  
  28.         $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());  
  29.    
  30.         // Selecing database  
  31.         $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());  
  32.    
  33.         // returing connection cursor  
  34.         return $con;  
  35.     }  
  36.    
  37.     /** 
  38.      * Function to close db connection 
  39.      */  
  40.     function close() {  
  41.         // closing db connection  
  42.         mysql_close();  
  43.     }  
  44.    
  45. }  
  46.    
  47. ?>  
怎麼調用:當你想連接MySQl數據庫或者執行某些操作時,可以這樣使用db_connect.php
  1. $dbnew DB_CONNECT(); // creating class object(will open database connection)  
6. 使用PHP執行基本CRUD操作

在這部分,我將講述使用PHP對MySQL數據庫執行基本CRUD(創建,讀取,更新,刪除)操作。

如果你是PHP和MySQL新手,我建議你可以先學習PHPSQL基礎知識。

6. a)在MYSQL中新建一行(創建一行新的產品)

在你的PHP項目中新建一個php文件,命名爲create_product.php,並輸入以下代碼。該文件主要實現在products表中插入一個新的產品。

在下面的代碼我使用POST來讀取產品數據並把他們存儲在products表中。

最後我會輸出一些JSON返回值,以便返回給客戶端(Android項目)

create_product.php

  1. <?php  
  2.    
  3. /* 
  4.  * Following code will create a new product row 
  5.  * All product details are read from HTTP Post Request 
  6.  */  
  7.    
  8. // array for JSON response  
  9. $response = array();  
  10.    
  11. // check for required fields  
  12. if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {  
  13.    
  14.     $name = $_POST['name'];  
  15.     $price = $_POST['price'];  
  16.     $description = $_POST['description'];  
  17.    
  18.     // include db connect class  
  19.     require_once __DIR__ . '/db_connect.php';  
  20.    
  21.     // connecting to db  
  22.     $db = new DB_CONNECT();  
  23.    
  24.     // mysql inserting a new row  
  25.     $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");  
  26.    
  27.     // check if row inserted or not  
  28.     if ($result) {  
  29.         // successfully inserted into database  
  30.         $response["success"] = 1;  
  31.         $response["message"] = "Product successfully created.";  
  32.    
  33.         // echoing JSON response  
  34.         echo json_encode($response);  
  35.     } else {  
  36.         // failed to insert row  
  37.         $response["success"] = 0;  
  38.         $response["message"] = "Oops! An error occurred.";  
  39.    
  40.         // echoing JSON response  
  41.         echo json_encode($response);  
  42.     }  
  43. else {  
  44.     // required field is missing  
  45.     $response["success"] = 0;  
  46.     $response["message"] = "Required field(s) is missing";  
  47.    
  48.     // echoing JSON response  
  49.     echo json_encode($response);  
  50. }  
  51. ?>  
對於上面的代碼,JSON的返回值會是:

當POST 參數丟失

  1. {   
  2. "success": 0,   
  3. "message""Required field(s) is missing"  
  4. }  
當product成功創建
  1. {   
  2. "success": 1,   
  3. "message""Product successfully created."  
  4. }  
當插入數據時出現錯誤
  1. {   
  2. "success": 0,   
  3. "message""Oops! An error occurred."  
  4. }  

實際測試的時候,出現Required field(s) is missing php錯誤,我把$_POST換成$_GET就對了,對應的NewProductActivity也要換成GET方法

6. b)從MySQL中讀取一行信息(讀取產品詳細信息)

創建一個新的php文件,命名爲get_product_details.php,寫入以下代碼。

該文件通過傳遞產品id作爲POST參數獲得單個產品的詳細信息

get_product_details.php

  1. <?php  
  2.    
  3. /* 
  4.  * Following code will get single product details 
  5.  * A product is identified by product id (pid) 
  6.  */  
  7.    
  8. // array for JSON response  
  9. $response = array();  
  10.    
  11. // include db connect class  
  12. require_once __DIR__ . '/db_connect.php';  
  13.    
  14. // connecting to db  
  15. $db = new DB_CONNECT();  
  16.    
  17. // check for post data  
  18. if (isset($_GET["pid"])) {  
  19.     $pid = $_GET['pid'];  
  20.    
  21.     // get a product from products table  
  22.     $result = mysql_query("SELECT *FROM products WHERE pid = $pid");  
  23.    
  24.     if (!empty($result)) {  
  25.         // check for empty result  
  26.         if (mysql_num_rows($result) > 0) {  
  27.    
  28.             $result = mysql_fetch_array($result);  
  29.    
  30.             $product = array();  
  31.             $product["pid"] = $result["pid"];  
  32.             $product["name"] = $result["name"];  
  33.             $product["price"] = $result["price"];  
  34.             $product["description"] = $result["description"];  
  35.             $product["created_at"] = $result["created_at"];  
  36.             $product["updated_at"] = $result["updated_at"];  
  37.             // success  
  38.             $response["success"] = 1;  
  39.    
  40.             // user node  
  41.             $response["product"] = array();  
  42.    
  43.             array_push($response["product"], $product);  
  44.    
  45.             // echoing JSON response  
  46.             echo json_encode($response);  
  47.         } else {  
  48.             // no product found  
  49.             $response["success"] = 0;  
  50.             $response["message"] = "No product found";  
  51.    
  52.             // echo no users JSON  
  53.             echo json_encode($response);  
  54.         }  
  55.     } else {  
  56.         // no product found  
  57.         $response["success"] = 0;  
  58.         $response["message"] = "No product found";  
  59.    
  60.         // echo no users JSON  
  61.         echo json_encode($response);  
  62.     }  
  63. else {  
  64.     // required field is missing  
  65.     $response["success"] = 0;  
  66.     $response["message"] = "Required field(s) is missing";  
  67.    
  68.     // echoing JSON response  
  69.     echo json_encode($response);  
  70. }  
  71. ?>  
  1. The json response for the above file will be  
  2. When successfully getting product details  
  3. {   
  4. "success": 1,   
  5. "product": [   
  6. {   
  7. "pid""1",   
  8. "name""iPHone 4S",   
  9. "price""300.00",   
  10. "description""iPhone 4S white",   
  11. "created_at""2012-04-29 01:41:42",   
  12. "updated_at""0000-00-00 00:00:00"  
  13. }   
  14. ]   
  15. }  
  16. When no product found with matched pid  
  17. {   
  18. "success": 0,   
  19. "message""No product found"  
  20. }  
6. c)從MySQL讀取所有行(讀取所有產品信息)

我們需要用json數據在Android設備上顯示所有的產品。

新建一個php文件,命名爲get_all_products.php,寫入以下代碼。

get_all_products.php

  1. <?php  
  2.    
  3. /* 
  4.  * Following code will list all the products 
  5.  */  
  6.    
  7. // array for JSON response  
  8. $response = array();  
  9.    
  10. // include db connect class  
  11. require_once __DIR__ . '/db_connect.php';  
  12.    
  13. // connecting to db  
  14. $db = new DB_CONNECT();  
  15.    
  16. // get all products from products table  
  17. $result = mysql_query("SELECT *FROM products"or die(mysql_error());  
  18.    
  19. // check for empty result  
  20. if (mysql_num_rows($result) > 0) {  
  21.     // looping through all results  
  22.     // products node  
  23.     $response["products"] = array();  
  24.    
  25.     while ($row = mysql_fetch_array($result)) {  
  26.         // temp user array  
  27.         $product = array();  
  28.         $product["pid"] = $row["pid"];  
  29.         $product["name"] = $row["name"];  
  30.         $product["price"] = $row["price"];  
  31.         $product["created_at"] = $row["created_at"];  
  32.         $product["updated_at"] = $row["updated_at"];  
  33.    
  34.         // push single product into final response array  
  35.         array_push($response["products"], $product);  
  36.     }  
  37.     // success  
  38.     $response["success"] = 1;  
  39.    
  40.     // echoing JSON response  
  41.     echo json_encode($response);  
  42. else {  
  43.     // no products found  
  44.     $response["success"] = 0;  
  45.     $response["message"] = "No products found";  
  46.    
  47.     // echo no users JSON  
  48.     echo json_encode($response);  
  49. }  
  50. ?>  
  51. And the JSON response for above code  
  52. Listing all Products  
  53. {   
  54. "products": [   
  55. {   
  56. "pid""1",   
  57. "name""iPhone 4S",   
  58. "price""300.00",   
  59. "created_at""2012-04-29 02:04:02",   
  60. "updated_at""0000-00-00 00:00:00"  
  61. },   
  62. {   
  63. "pid""2",   
  64. "name""Macbook Pro",   
  65. "price""600.00",   
  66. "created_at""2012-04-29 02:04:51",   
  67. "updated_at""0000-00-00 00:00:00"  
  68. },   
  69. {   
  70. "pid""3",   
  71. "name""Macbook Air",   
  72. "price""800.00",   
  73. "created_at""2012-04-29 02:05:57",   
  74. "updated_at""0000-00-00 00:00:00"  
  75. },   
  76. {   
  77. "pid""4",   
  78. "name""OS X Lion",   
  79. "price""100.00",   
  80. "created_at""2012-04-29 02:07:14",   
  81. "updated_at""0000-00-00 00:00:00"  
  82. }   
  83. ],   
  84. "success": 1  
  85. }  
  86. When products not found  
  87. {   
  88. "success": 0,   
  89. "message""No products found"  
  90. }  
6. d)在MySQL中更新某一行(更新產品詳細信息)

新建一個php文件,命名爲update_product.php。每一個產品通過pid標識。

update_product.php

  1. <?php  
  2.    
  3. /* 
  4.  * Following code will update a product information 
  5.  * A product is identified by product id (pid) 
  6.  */  
  7.    
  8. // array for JSON response  
  9. $response = array();  
  10.    
  11. // check for required fields  
  12. if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {  
  13.    
  14.     $pid = $_POST['pid'];  
  15.     $name = $_POST['name'];  
  16.     $price = $_POST['price'];  
  17.     $description = $_POST['description'];  
  18.    
  19.     // include db connect class  
  20.     require_once __DIR__ . '/db_connect.php';  
  21.    
  22.     // connecting to db  
  23.     $db = new DB_CONNECT();  
  24.    
  25.     // mysql update row with matched pid  
  26.     $result = mysql_query("UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");  
  27.    
  28.     // check if row inserted or not  
  29.     if ($result) {  
  30.         // successfully updated  
  31.         $response["success"] = 1;  
  32.         $response["message"] = "Product successfully updated.";  
  33.    
  34.         // echoing JSON response  
  35.         echo json_encode($response);  
  36.     } else {  
  37.    
  38.     }  
  39. else {  
  40.     // required field is missing  
  41.     $response["success"] = 0;  
  42.     $response["message"] = "Required field(s) is missing";  
  43.    
  44.     // echoing JSON response  
  45.     echo json_encode($response);  
  46. }  
  47. ?>  
  1. The json reponse of above code, when product is updated successfully  
  2. {   
  3. "success": 1,   
  4. "message""Product successfully updated."  
  5. }  
6. e)在MySQL中刪除某一行(刪除一個產品)

新建一個php文件,命名爲delete_product.php。該文件主要功能是從數據庫中刪除一個產品。

delete_product.php

  1. <?php  
  2.    
  3. /* 
  4.  * Following code will delete a product from table 
  5.  * A product is identified by product id (pid) 
  6.  */  
  7.    
  8. // array for JSON response  
  9. $response = array();  
  10.    
  11. // check for required fields  
  12. if (isset($_POST['pid'])) {  
  13.     $pid = $_POST['pid'];  
  14.    
  15.     // include db connect class  
  16.     require_once __DIR__ . '/db_connect.php';  
  17.    
  18.     // connecting to db  
  19.     $db = new DB_CONNECT();  
  20.    
  21.     // mysql update row with matched pid  
  22.     $result = mysql_query("DELETE FROM products WHERE pid = $pid");  
  23.    
  24.     // check if row deleted or not  
  25.     if (mysql_affected_rows() > 0) {  
  26.         // successfully updated  
  27.         $response["success"] = 1;  
  28.         $response["message"] = "Product successfully deleted";  
  29.    
  30.         // echoing JSON response  
  31.         echo json_encode($response);  
  32.     } else {  
  33.         // no product found  
  34.         $response["success"] = 0;  
  35.         $response["message"] = "No product found";  
  36.    
  37.         // echo no users JSON  
  38.         echo json_encode($response);  
  39.     }  
  40. else {  
  41.     // required field is missing  
  42.     $response["success"] = 0;  
  43.     $response["message"] = "Required field(s) is missing";  
  44.    
  45.     // echoing JSON response  
  46.     echo json_encode($response);  
  47. }  
  48. ?>  
  1. When product successfully deleted  
  2. {   
  3. "success": 1,   
  4. "message""Product successfully deleted"  
  5. }  
  6. When product not found  
  7. {   
  8. "success": 0,   
  9. "message""No product found"  
  10. }  
到目前爲止,我們爲products表建立了一個簡單的接口。服務器端編程已經完成了,接下來讓我們開始真正的Android應用程序編程。

7. 新建一個Android應用程序

在Eclipse IDE中創建一個新項目,填寫所需的細節信息。

1. 新建項目,在菜單中選擇File->New->Android Project,把Activity類命名爲MainScreenActivity

2. 打開AndroidManifest.xml,添加以下代碼。我先在manifest文件中添加了所需的全部Activity類。同樣需要添加INTERNET連接權限(非常重要)
AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.androidhive"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.    
  9.     <application  
  10.         android:configChanges="keyboardHidden|orientation"  
  11.         android:icon="@drawable/ic_launcher"  
  12.         android:label="@string/app_name" >  
  13.    
  14.         <activity  
  15.             android:name=".MainScreenActivity"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.    
  20.                 <category android:name="android.intent.category.LAUNCHER" />  
  21.             </intent-filter>  
  22.         </activity>  
  23.    
  24.         <!-- All Product Activity -->  
  25.         <activity  
  26.             android:name=".AllProductsActivity"  
  27.             android:label="All Products" >  
  28.         </activity>  
  29.    
  30.         <!-- Add Product Activity -->  
  31.         <activity  
  32.             android:name=".NewProductActivity"  
  33.             android:label="Add New Product" >  
  34.         </activity>  
  35.    
  36.         <!-- Edit Product Activity -->  
  37.         <activity  
  38.             android:name=".EditProductActivity"  
  39.             android:label="Edit Product" >  
  40.         </activity>  
  41.     </application>  
  42.    
  43.     <!--  Internet Permissions -->  
  44.     <uses-permission android:name="android.permission.INTERNET" />  
  45.    
  46. </manifest>  
3. 在res->layout文件夾下新建一個xml文件,命名爲mian_screen.xml。這個layout文件包含兩個簡單的按鈕,通過這兩個按鈕可以查看所有產品和添加新產品。如下圖所示

main_screen.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical"  
  6.     android:gravity="center_horizontal">  
  7.    
  8.     <!--  Sample Dashboard screen with Two buttons -->  
  9.     <!--  Button to view all products screen -->  
  10.     <Button android:id="@+id/btnViewProducts"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:text="View Products"  
  14.         android:layout_marginTop="25dip"/>  
  15.    
  16.     <!--  Button to create a new product screen -->  
  17.     <Button android:id="@+id/btnCreateProduct"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="Add New Products"  
  21.         android:layout_marginTop="25dip"/>  
  22.    
  23. </LinearLayout>  




4. 打開MainScreenActivity.java爲main_screen.xml文件裏的兩個按鈕添加點擊事件

MainScreenActivity.java

  1. package com.example.androidhive;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8.    
  9. public class MainScreenActivity extends Activity{  
  10.    
  11.     Button btnViewProducts;  
  12.     Button btnNewProduct;  
  13.    
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main_screen);  
  18.    
  19.         // Buttons  
  20.         btnViewProducts = (Button) findViewById(R.id.btnViewProducts);  
  21.         btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);  
  22.    
  23.         // view products click event  
  24.         btnViewProducts.setOnClickListener(new View.OnClickListener() {  
  25.    
  26.             @Override  
  27.             public void onClick(View view) {  
  28.                 // Launching All products Activity  
  29.                 Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);  
  30.                 startActivity(i);  
  31.    
  32.             }  
  33.         });  
  34.    
  35.         // view products click event  
  36.         btnNewProduct.setOnClickListener(new View.OnClickListener() {  
  37.    
  38.             @Override  
  39.             public void onClick(View view) {  
  40.                 // Launching create new product activity  
  41.                 Intent i = new Intent(getApplicationContext(), NewProductActivity.class);  
  42.                 startActivity(i);  
  43.    
  44.             }  
  45.         });  
  46.     }  
  47. }  
5. 在ListView中顯示所有產品(讀取)

現在我們需要一個Activity來以列表的形式顯示所有產品。如我們所知,使用ListView需要兩個xml文件,一個是列表佈局,另一個是單個的列表項佈局。在res->layout文件夾下新建兩個xml文件:all_product.xml和list_item.xml
all_product.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical">  
  6.     <!-- Main ListView  
  7.          Always give id value as list(@android:id/list)  
  8.     -->  
  9.     <ListView  
  10.         android:id="@android:id/list"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"/>  
  13.    
  14. </LinearLayout>  
list_item.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.    
  7.     <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->  
  8.     <TextView  
  9.         android:id="@+id/pid"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:visibility="gone" />  
  13.    
  14.     <!-- Name Label -->  
  15.     <TextView  
  16.         android:id="@+id/name"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:paddingTop="6dip"  
  20.         android:paddingLeft="6dip"  
  21.         android:textSize="17dip"  
  22.         android:textStyle="bold" />  
  23.    
  24. </LinearLayout>  
6. 新建一個名爲AllProductActivity.java的類文件。

在下面的代碼中,

首先,在後臺AsyncTask線程中發送一個請求給get_all_products.php

然後,從get_all_products.php獲取JSON格式的數據,我爲json轉換了格式(parser),並使其顯示在ListView中。

如果沒有找到產品,會跳轉到AddNewProductActivity

AllProductActivity.java

  1. package com.example.androidhive;  
  2.    
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6.    
  7. import org.apache.http.NameValuePair;  
  8. import org.json.JSONArray;  
  9. import org.json.JSONException;  
  10. import org.json.JSONObject;  
  11.    
  12. import android.app.ListActivity;  
  13. import android.app.ProgressDialog;  
  14. import android.content.Intent;  
  15. import android.os.AsyncTask;  
  16. import android.os.Bundle;  
  17. import android.util.Log;  
  18. import android.view.View;  
  19. import android.widget.AdapterView;  
  20. import android.widget.AdapterView.OnItemClickListener;  
  21. import android.widget.ListAdapter;  
  22. import android.widget.ListView;  
  23. import android.widget.SimpleAdapter;  
  24. import android.widget.TextView;  
  25.    
  26. public class AllProductsActivity extends ListActivity {  
  27.    
  28.     // Progress Dialog  
  29.     private ProgressDialog pDialog;  
  30.    
  31.     // Creating JSON Parser object  
  32.     JSONParser jParser = new JSONParser();  
  33.    
  34.     ArrayList<HashMap<String, String>> productsList;  
  35.    
  36.     // url to get all products list  
  37.     private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";  
  38.    
  39.     // JSON Node names  
  40.     private static final String TAG_SUCCESS = "success";  
  41.     private static final String TAG_PRODUCTS = "products";  
  42.     private static final String TAG_PID = "pid";  
  43.     private static final String TAG_NAME = "name";  
  44.    
  45.     // products JSONArray  
  46.     JSONArray products = null;  
  47.    
  48.     @Override  
  49.     public void onCreate(Bundle savedInstanceState) {  
  50.         super.onCreate(savedInstanceState);  
  51.         setContentView(R.layout.all_products);  
  52.    
  53.         // Hashmap for ListView  
  54.         productsList = new ArrayList<HashMap<String, String>>();  
  55.    
  56.         // Loading products in Background Thread  
  57.         new LoadAllProducts().execute();  
  58.    
  59.         // Get listview  
  60.         ListView lv = getListView();  
  61.    
  62.         // on seleting single product  
  63.         // launching Edit Product Screen  
  64.         lv.setOnItemClickListener(new OnItemClickListener() {  
  65.    
  66.             @Override  
  67.             public void onItemClick(AdapterView<?> parent, View view,  
  68.                     int position, long id) {  
  69.                 // getting values from selected ListItem  
  70.                 String pid = ((TextView) view.findViewById(R.id.pid)).getText()  
  71.                         .toString();  
  72.    
  73.                 // Starting new intent  
  74.                 Intent in = new Intent(getApplicationContext(),  
  75.                         EditProductActivity.class);  
  76.                 // sending pid to next activity  
  77.                 in.putExtra(TAG_PID, pid);  
  78.    
  79.                 // starting new activity and expecting some response back  
  80.                 startActivityForResult(in, 100);  
  81.             }  
  82.         });  
  83.    
  84.     }  
  85.    
  86.     // Response from Edit Product Activity  
  87.     @Override  
  88.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  89.         super.onActivityResult(requestCode, resultCode, data);  
  90.         // if result code 100  
  91.         if (resultCode == 100) {  
  92.             // if result code 100 is received  
  93.             // means user edited/deleted product  
  94.             // reload this screen again  
  95.             Intent intent = getIntent();  
  96.             finish();  
  97.             startActivity(intent);  
  98.         }  
  99.    
  100.     }  
  101.    
  102.     /** 
  103.      * Background Async Task to Load all product by making HTTP Request 
  104.      * */  
  105.     class LoadAllProducts extends AsyncTask<String, String, String> {  
  106.    
  107.         /** 
  108.          * Before starting background thread Show Progress Dialog 
  109.          * */  
  110.         @Override  
  111.         protected void onPreExecute() {  
  112.             super.onPreExecute();  
  113.             pDialog = new ProgressDialog(AllProductsActivity.this);  
  114.             pDialog.setMessage("Loading products. Please wait...");  
  115.             pDialog.setIndeterminate(false);  
  116.             pDialog.setCancelable(false);  
  117.             pDialog.show();  
  118.         }  
  119.    
  120.         /** 
  121.          * getting All products from url 
  122.          * */  
  123.         protected String doInBackground(String... args) {  
  124.             // Building Parameters  
  125.             List<NameValuePair> params = new ArrayList<NameValuePair>();  
  126.             // getting JSON string from URL  
  127.             JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);  
  128.    
  129.             // Check your log cat for JSON reponse  
  130.             Log.d("All Products: ", json.toString());  
  131.    
  132.             try {  
  133.                 // Checking for SUCCESS TAG  
  134.                 int success = json.getInt(TAG_SUCCESS);  
  135.    
  136.                 if (success == 1) {  
  137.                     // products found  
  138.                     // Getting Array of Products  
  139.                     products = json.getJSONArray(TAG_PRODUCTS);  
  140.    
  141.                     // looping through All Products  
  142.                     for (int i = 0; i < products.length(); i++) {  
  143.                         JSONObject c = products.getJSONObject(i);  
  144.    
  145.                         // Storing each json item in variable  
  146.                         String id = c.getString(TAG_PID);  
  147.                         String name = c.getString(TAG_NAME);  
  148.    
  149.                         // creating new HashMap  
  150.                         HashMap<String, String> map = new HashMap<String, String>();  
  151.    
  152.                         // adding each child node to HashMap key => value  
  153.                         map.put(TAG_PID, id);  
  154.                         map.put(TAG_NAME, name);  
  155.    
  156.                         // adding HashList to ArrayList  
  157.                         productsList.add(map);  
  158.                     }  
  159.                 } else {  
  160.                     // no products found  
  161.                     // Launch Add New product Activity  
  162.                     Intent i = new Intent(getApplicationContext(),  
  163.                             NewProductActivity.class);  
  164.                     // Closing all previous activities  
  165.                     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  166.                     startActivity(i);  
  167.                 }  
  168.             } catch (JSONException e) {  
  169.                 e.printStackTrace();  
  170.             }  
  171.    
  172.             return null;  
  173.         }  
  174.    
  175.         /** 
  176.          * After completing background task Dismiss the progress dialog 
  177.          * **/  
  178.         protected void onPostExecute(String file_url) {  
  179.             // dismiss the dialog after getting all products  
  180.             pDialog.dismiss();  
  181.             // updating UI from Background Thread  
  182.             runOnUiThread(new Runnable() {  
  183.                 public void run() {  
  184.                     /** 
  185.                      * Updating parsed JSON data into ListView 
  186.                      * */  
  187.                     ListAdapter adapter = new SimpleAdapter(  
  188.                             AllProductsActivity.this, productsList,  
  189.                             R.layout.list_item, new String[] { TAG_PID,  
  190.                                     TAG_NAME},  
  191.                             new int[] { R.id.pid, R.id.name });  
  192.                     // updating listview  
  193.                     setListAdapter(adapter);  
  194.                 }  
  195.             });  
  196.    
  197.         }  
  198.    
  199.     }  
  200. }  

7. 添加一個新產品(寫入)

創建一個新的view和activity來向MySQL數據庫添加新產品。

新建一個簡單的表單,創建提供輸入產品名稱,價格和描述的EditText

add_product.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.    
  7.     <!-- Name Label -->  
  8.     <TextView android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Product Name"  
  11.         android:paddingLeft="10dip"  
  12.         android:paddingRight="10dip"  
  13.         android:paddingTop="10dip"  
  14.         android:textSize="17dip"/>  
  15.    
  16.     <!-- Input Name -->  
  17.     <EditText android:id="@+id/inputName"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_margin="5dip"  
  21.         android:layout_marginBottom="15dip"  
  22.         android:singleLine="true"/>  
  23.    
  24.     <!-- Price Label -->  
  25.     <TextView android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="Price"  
  28.         android:paddingLeft="10dip"  
  29.         android:paddingRight="10dip"  
  30.         android:paddingTop="10dip"  
  31.         android:textSize="17dip"/>  
  32.    
  33.     <!-- Input Price -->  
  34.     <EditText android:id="@+id/inputPrice"  
  35.         android:layout_width="fill_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:layout_margin="5dip"  
  38.         android:layout_marginBottom="15dip"  
  39.         android:singleLine="true"  
  40.         android:inputType="numberDecimal"/>  
  41.    
  42.     <!-- Description Label -->  
  43.     <TextView android:layout_width="fill_parent"  
  44.         android:layout_height="wrap_content"  
  45.         android:text="Description"  
  46.         android:paddingLeft="10dip"  
  47.         android:paddingRight="10dip"  
  48.         android:paddingTop="10dip"  
  49.         android:textSize="17dip"/>  
  50.    
  51.     <!-- Input description -->  
  52.     <EditText android:id="@+id/inputDesc"  
  53.         android:layout_width="fill_parent"  
  54.         android:layout_height="wrap_content"  
  55.         android:layout_margin="5dip"  
  56.         android:layout_marginBottom="15dip"  
  57.         android:lines="4"  
  58.         android:gravity="top"/>  
  59.    
  60.     <!-- Button Create Product -->  
  61.     <Button android:id="@+id/btnCreateProduct"  
  62.         android:layout_width="fill_parent"  
  63.         android:layout_height="wrap_content"  
  64.         android:text="Create Product"/>  
  65.    
  66. </LinearLayout>  

8. 新建一個Activity來處理向MySQL數據庫插入新產品。

新建名爲NewProductActivity.java的文件,輸入以下代碼。在下面的代碼中

首先,從EditText獲得用戶輸入的產品數據,格式化成基本參數格式

然後,向create_product.php發送請求,通過HTTP POST創建一個新的產品

最後,從create_product.php獲取json返回值,如果success值爲1,新得到的列表中就加入了新增的產品。

NewProductActivity.java

  1. package com.example.androidhive;  
  2.    
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.    
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.message.BasicNameValuePair;  
  8. import org.json.JSONException;  
  9. import org.json.JSONObject;  
  10.    
  11. import android.app.Activity;  
  12. import android.app.ProgressDialog;  
  13. import android.content.Intent;  
  14. import android.os.AsyncTask;  
  15. import android.os.Bundle;  
  16. import android.util.Log;  
  17. import android.view.View;  
  18. import android.widget.Button;  
  19. import android.widget.EditText;  
  20.    
  21. public class NewProductActivity extends Activity {  
  22.    
  23.     // Progress Dialog  
  24.     private ProgressDialog pDialog;  
  25.    
  26.     JSONParser jsonParser = new JSONParser();  
  27.     EditText inputName;  
  28.     EditText inputPrice;  
  29.     EditText inputDesc;  
  30.    
  31.     // url to create new product  
  32.     private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";  
  33.    
  34.     // JSON Node names  
  35.     private static final String TAG_SUCCESS = "success";  
  36.    
  37.     @Override  
  38.     public void onCreate(Bundle savedInstanceState) {  
  39.         super.onCreate(savedInstanceState);  
  40.         setContentView(R.layout.add_product);  
  41.    
  42.         // Edit Text  
  43.         inputName = (EditText) findViewById(R.id.inputName);  
  44.         inputPrice = (EditText) findViewById(R.id.inputPrice);  
  45.         inputDesc = (EditText) findViewById(R.id.inputDesc);  
  46.    
  47.         // Create button  
  48.         Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);  
  49.    
  50.         // button click event  
  51.         btnCreateProduct.setOnClickListener(new View.OnClickListener() {  
  52.    
  53.             @Override  
  54.             public void onClick(View view) {  
  55.                 // creating new product in background thread  
  56.                 new CreateNewProduct().execute();  
  57.             }  
  58.         });  
  59.     }  
  60.    
  61.     /** 
  62.      * Background Async Task to Create new product 
  63.      * */  
  64.     class CreateNewProduct extends AsyncTask<String, String, String> {  
  65.    
  66.         /** 
  67.          * Before starting background thread Show Progress Dialog 
  68.          * */  
  69.         @Override  
  70.         protected void onPreExecute() {  
  71.             super.onPreExecute();  
  72.             pDialog = new ProgressDialog(NewProductActivity.this);  
  73.             pDialog.setMessage("Creating Product..");  
  74.             pDialog.setIndeterminate(false);  
  75.             pDialog.setCancelable(true);  
  76.             pDialog.show();  
  77.         }  
  78.    
  79.         /** 
  80.          * Creating product 
  81.          * */  
  82.         protected String doInBackground(String... args) {  
  83.             String name = inputName.getText().toString();  
  84.             String price = inputPrice.getText().toString();  
  85.             String description = inputDesc.getText().toString();  
  86.    
  87.             // Building Parameters  
  88.             List<NameValuePair> params = new ArrayList<NameValuePair>();  
  89.             params.add(new BasicNameValuePair("name", name));  
  90.             params.add(new BasicNameValuePair("price", price));  
  91.             params.add(new BasicNameValuePair("description", description));  
  92.    
  93.             // getting JSON Object  
  94.             // Note that create product url accepts POST method  
  95.             JSONObject json = jsonParser.makeHttpRequest(url_create_product,  
  96.                     "POST", params);  
  97.    
  98.             // check log cat fro response  
  99.             Log.d("Create Response", json.toString());  
  100.    
  101.             // check for success tag  
  102.             try {  
  103.                 int success = json.getInt(TAG_SUCCESS);  
  104.    
  105.                 if (success == 1) {  
  106.                     // successfully created product  
  107.                     Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);  
  108.                     startActivity(i);  
  109.    
  110.                     // closing this screen  
  111.                     finish();  
  112.                 } else {  
  113.                     // failed to create product  
  114.                 }  
  115.             } catch (JSONException e) {  
  116.                 e.printStackTrace();  
  117.             }  
  118.    
  119.             return null;  
  120.         }  
  121.    
  122.         /** 
  123.          * After completing background task Dismiss the progress dialog 
  124.          * **/  
  125.         protected void onPostExecute(String file_url) {  
  126.             // dismiss the dialog once done  
  127.             pDialog.dismiss();  
  128.         }  
  129.    
  130.     }  
  131. }  
9. 讀取,更新,刪除一項產品

你稍加註意就會發現,在AllProductsActivity.java中,選中列表的某一項,會進入EditProductActivity.java。

接下來新建一個名爲edit_product,xml的xml文件,創建類似create_product,xml的表單。

edit_product,xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.    
  7.     <!-- Name Label -->  
  8.     <TextView android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Product Name"  
  11.         android:paddingLeft="10dip"  
  12.         android:paddingRight="10dip"  
  13.         android:paddingTop="10dip"  
  14.         android:textSize="17dip"/>  
  15.    
  16.     <!-- Input Name -->  
  17.     <EditText android:id="@+id/inputName"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_margin="5dip"  
  21.         android:layout_marginBottom="15dip"  
  22.         android:singleLine="true"/>  
  23.    
  24.     <!-- Price Label -->  
  25.     <TextView android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="Price"  
  28.         android:paddingLeft="10dip"  
  29.         android:paddingRight="10dip"  
  30.         android:paddingTop="10dip"  
  31.         android:textSize="17dip"/>  
  32.    
  33.     <!-- Input Price -->  
  34.     <EditText android:id="@+id/inputPrice"  
  35.         android:layout_width="fill_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:layout_margin="5dip"  
  38.         android:layout_marginBottom="15dip"  
  39.         android:singleLine="true"  
  40.         android:inputType="numberDecimal"/>  
  41.    
  42.     <!-- Description Label -->  
  43.     <TextView android:layout_width="fill_parent"  
  44.         android:layout_height="wrap_content"  
  45.         android:text="Description"  
  46.         android:paddingLeft="10dip"  
  47.         android:paddingRight="10dip"  
  48.         android:paddingTop="10dip"  
  49.         android:textSize="17dip"/>  
  50.    
  51.     <!-- Input description -->  
  52.     <EditText android:id="@+id/inputDesc"  
  53.         android:layout_width="fill_parent"  
  54.         android:layout_height="wrap_content"  
  55.         android:layout_margin="5dip"  
  56.         android:layout_marginBottom="15dip"  
  57.         android:lines="4"  
  58.         android:gravity="top"/>  
  59.    
  60.     <LinearLayout android:layout_width="fill_parent"  
  61.         android:layout_height="wrap_content"  
  62.         android:orientation="horizontal">  
  63.         <!-- Button Create Product -->  
  64.     <Button android:id="@+id/btnSave"  
  65.         android:layout_width="fill_parent"  
  66.         android:layout_height="wrap_content"  
  67.         android:text="Save Changes"  
  68.         android:layout_weight="1"/>  
  69.    
  70.     <!-- Button Create Product -->  
  71.     <Button android:id="@+id/btnDelete"  
  72.         android:layout_width="fill_parent"  
  73.         android:layout_height="wrap_content"  
  74.         android:text="Delete"  
  75.         android:layout_weight="1"/>  
  76.     </LinearLayout>  
  77.    
  78. </LinearLayout>  
10. 對應edit_product.xml新建EditProductActivity.java,並輸入下列代碼。

在以下代碼中:

首先,從intent中讀取發送給ListView的產品id(pid)

然後,向get_product_details.php發送請求,獲得json格式的產品詳細信息,把它顯示在EditText中。

然後,當產品信息顯示在表單中後,如果用戶點擊保存按鈕,會向update_product.php發送另一個HTTP請求,更新數據庫中的產品信息

如果用戶點擊刪除按鈕,將會向delete_product.php發送請求,該產品慧聰MySQL數據庫中刪除,ListView刷新後顯示新的產品列表。

EditProductActivity.java

  1. package com.example.androidhive;  
  2.    
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.    
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.message.BasicNameValuePair;  
  8. import org.json.JSONArray;  
  9. import org.json.JSONException;  
  10. import org.json.JSONObject;  
  11.    
  12. import android.app.Activity;  
  13. import android.app.ProgressDialog;  
  14. import android.content.Intent;  
  15. import android.os.AsyncTask;  
  16. import android.os.Bundle;  
  17. import android.util.Log;  
  18. import android.view.View;  
  19. import android.widget.Button;  
  20. import android.widget.EditText;  
  21.    
  22. public class EditProductActivity extends Activity {  
  23.    
  24.     EditText txtName;  
  25.     EditText txtPrice;  
  26.     EditText txtDesc;  
  27.     EditText txtCreatedAt;  
  28.     Button btnSave;  
  29.     Button btnDelete;  
  30.    
  31.     String pid;  
  32.    
  33.     // Progress Dialog  
  34.     private ProgressDialog pDialog;  
  35.    
  36.     // JSON parser class  
  37.     JSONParser jsonParser = new JSONParser();  
  38.    
  39.     // single product url  
  40.     private static final String url_product_detials = "http://api.androidhive.info/android_connect/get_product_details.php";  
  41.    
  42.     // url to update product  
  43.     private static final String url_update_product = "http://api.androidhive.info/android_connect/update_product.php";  
  44.    
  45.     // url to delete product  
  46.     private static final String url_delete_product = "http://api.androidhive.info/android_connect/delete_product.php";  
  47.    
  48.     // JSON Node names  
  49.     private static final String TAG_SUCCESS = "success";  
  50.     private static final String TAG_PRODUCT = "product";  
  51.     private static final String TAG_PID = "pid";  
  52.     private static final String TAG_NAME = "name";  
  53.     private static final String TAG_PRICE = "price";  
  54.     private static final String TAG_DESCRIPTION = "description";  
  55.    
  56.     @Override  
  57.     public void onCreate(Bundle savedInstanceState) {  
  58.         super.onCreate(savedInstanceState);  
  59.         setContentView(R.layout.edit_product);  
  60.    
  61.         // save button  
  62.         btnSave = (Button) findViewById(R.id.btnSave);  
  63.         btnDelete = (Button) findViewById(R.id.btnDelete);  
  64.    
  65.         // getting product details from intent  
  66.         Intent i = getIntent();  
  67.    
  68.         // getting product id (pid) from intent  
  69.         pid = i.getStringExtra(TAG_PID);  
  70.    
  71.         // Getting complete product details in background thread  
  72.         new GetProductDetails().execute();  
  73.    
  74.         // save button click event  
  75.         btnSave.setOnClickListener(new View.OnClickListener() {  
  76.    
  77.             @Override  
  78.             public void onClick(View arg0) {  
  79.                 // starting background task to update product  
  80.                 new SaveProductDetails().execute();  
  81.             }  
  82.         });  
  83.    
  84.         // Delete button click event  
  85.         btnDelete.setOnClickListener(new View.OnClickListener() {  
  86.    
  87.             @Override  
  88.             public void onClick(View arg0) {  
  89.                 // deleting product in background thread  
  90.                 new DeleteProduct().execute();  
  91.             }  
  92.         });  
  93.    
  94.     }  
  95.    
  96.     /** 
  97.      * Background Async Task to Get complete product details 
  98.      * */  
  99.     class GetProductDetails extends AsyncTask<String, String, String> {  
  100.    
  101.         /** 
  102.          * Before starting background thread Show Progress Dialog 
  103.          * */  
  104.         @Override  
  105.         protected void onPreExecute() {  
  106.             super.onPreExecute();  
  107.             pDialog = new ProgressDialog(EditProductActivity.this);  
  108.             pDialog.setMessage("Loading product details. Please wait...");  
  109.             pDialog.setIndeterminate(false);  
  110.             pDialog.setCancelable(true);  
  111.             pDialog.show();  
  112.         }  
  113.    
  114.         /** 
  115.          * Getting product details in background thread 
  116.          * */  
  117.         protected String doInBackground(String... params) {  
  118.    
  119.             // updating UI from Background Thread  
  120.             runOnUiThread(new Runnable() {  
  121.                 public void run() {  
  122.                     // Check for success tag  
  123.                     int success;  
  124.                     try {  
  125.                         // Building Parameters  
  126.                         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  127.                         params.add(new BasicNameValuePair("pid", pid));  
  128.    
  129.                         // getting product details by making HTTP request  
  130.                         // Note that product details url will use GET request  
  131.                         JSONObject json = jsonParser.makeHttpRequest(  
  132.                                 url_product_detials, "GET", params);  
  133.    
  134.                         // check your log for json response  
  135.                         Log.d("Single Product Details", json.toString());  
  136.    
  137.                         // json success tag  
  138.                         success = json.getInt(TAG_SUCCESS);  
  139.                         if (success == 1) {  
  140.                             // successfully received product details  
  141.                             JSONArray productObj = json  
  142.                                     .getJSONArray(TAG_PRODUCT); // JSON Array  
  143.    
  144.                             // get first product object from JSON Array  
  145.                             JSONObject product = productObj.getJSONObject(0);  
  146.    
  147.                             // product with this pid found  
  148.                             // Edit Text  
  149.                             txtName = (EditText) findViewById(R.id.inputName);  
  150.                             txtPrice = (EditText) findViewById(R.id.inputPrice);  
  151.                             txtDesc = (EditText) findViewById(R.id.inputDesc);  
  152.    
  153.                             // display product data in EditText  
  154.                             txtName.setText(product.getString(TAG_NAME));  
  155.                             txtPrice.setText(product.getString(TAG_PRICE));  
  156.                             txtDesc.setText(product.getString(TAG_DESCRIPTION));  
  157.    
  158.                         }else{  
  159.                             // product with pid not found  
  160.                         }  
  161.                     } catch (JSONException e) {  
  162.                         e.printStackTrace();  
  163.                     }  
  164.                 }  
  165.             });  
  166.    
  167.             return null;  
  168.         }  
  169.    
  170.         /** 
  171.          * After completing background task Dismiss the progress dialog 
  172.          * **/  
  173.         protected void onPostExecute(String file_url) {  
  174.             // dismiss the dialog once got all details  
  175.             pDialog.dismiss();  
  176.         }  
  177.     }  
  178.    
  179.     /** 
  180.      * Background Async Task to  Save product Details 
  181.      * */  
  182.     class SaveProductDetails extends AsyncTask<String, String, String> {  
  183.    
  184.         /** 
  185.          * Before starting background thread Show Progress Dialog 
  186.          * */  
  187.         @Override  
  188.         protected void onPreExecute() {  
  189.             super.onPreExecute();  
  190.             pDialog = new ProgressDialog(EditProductActivity.this);  
  191.             pDialog.setMessage("Saving product ...");  
  192.             pDialog.setIndeterminate(false);  
  193.             pDialog.setCancelable(true);  
  194.             pDialog.show();  
  195.         }  
  196.    
  197.         /** 
  198.          * Saving product 
  199.          * */  
  200.         protected String doInBackground(String... args) {  
  201.    
  202.             // getting updated data from EditTexts  
  203.             String name = txtName.getText().toString();  
  204.             String price = txtPrice.getText().toString();  
  205.             String description = txtDesc.getText().toString();  
  206.    
  207.             // Building Parameters  
  208.             List<NameValuePair> params = new ArrayList<NameValuePair>();  
  209.             params.add(new BasicNameValuePair(TAG_PID, pid));  
  210.             params.add(new BasicNameValuePair(TAG_NAME, name));  
  211.             params.add(new BasicNameValuePair(TAG_PRICE, price));  
  212.             params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));  
  213.    
  214.             // sending modified data through http request  
  215.             // Notice that update product url accepts POST method  
  216.             JSONObject json = jsonParser.makeHttpRequest(url_update_product,  
  217.                     "POST", params);  
  218.    
  219.             // check json success tag  
  220.             try {  
  221.                 int success = json.getInt(TAG_SUCCESS);  
  222.    
  223.                 if (success == 1) {  
  224.                     // successfully updated  
  225.                     Intent i = getIntent();  
  226.                     // send result code 100 to notify about product update  
  227.                     setResult(100, i);  
  228.                     finish();  
  229.                 } else {  
  230.                     // failed to update product  
  231.                 }  
  232.             } catch (JSONException e) {  
  233.                 e.printStackTrace();  
  234.             }  
  235.    
  236.             return null;  
  237.         }  
  238.    
  239.         /** 
  240.          * After completing background task Dismiss the progress dialog 
  241.          * **/  
  242.         protected void onPostExecute(String file_url) {  
  243.             // dismiss the dialog once product uupdated  
  244.             pDialog.dismiss();  
  245.         }  
  246.     }  
  247.    
  248.     /***************************************************************** 
  249.      * Background Async Task to Delete Product 
  250.      * */  
  251.     class DeleteProduct extends AsyncTask<String, String, String> {  
  252.    
  253.         /** 
  254.          * Before starting background thread Show Progress Dialog 
  255.          * */  
  256.         @Override  
  257.         protected void onPreExecute() {  
  258.             super.onPreExecute();  
  259.             pDialog = new ProgressDialog(EditProductActivity.this);  
  260.             pDialog.setMessage("Deleting Product...");  
  261.             pDialog.setIndeterminate(false);  
  262.             pDialog.setCancelable(true);  
  263.             pDialog.show();  
  264.         }  
  265.    
  266.         /** 
  267.          * Deleting product 
  268.          * */  
  269.         protected String doInBackground(String... args) {  
  270.    
  271.             // Check for success tag  
  272.             int success;  
  273.             try {  
  274.                 // Building Parameters  
  275.                 List<NameValuePair> params = new ArrayList<NameValuePair>();  
  276.                 params.add(new BasicNameValuePair("pid", pid));  
  277.    
  278.                 // getting product details by making HTTP request  
  279.                 JSONObject json = jsonParser.makeHttpRequest(  
  280.                         url_delete_product, "POST", params);  
  281.    
  282.                 // check your log for json response  
  283.                 Log.d("Delete Product", json.toString());  
  284.    
  285.                 // json success tag  
  286.                 success = json.getInt(TAG_SUCCESS);  
  287.                 if (success == 1) {  
  288.                     // product successfully deleted  
  289.                     // notify previous activity by sending code 100  
  290.                     Intent i = getIntent();  
  291.                     // send result code 100 to notify about product deletion  
  292.                     setResult(100, i);  
  293.                     finish();  
  294.                 }  
  295.             } catch (JSONException e) {  
  296.                 e.printStackTrace();  
  297.             }  
  298.    
  299.             return null;  
  300.         }  
  301.    
  302.         /** 
  303.          * After completing background task Dismiss the progress dialog 
  304.          * **/  
  305.         protected void onPostExecute(String file_url) {  
  306.             // dismiss the dialog once product deleted  
  307.             pDialog.dismiss();  
  308.    
  309.         }  
  310.    
  311.     }  
  312. }  

11. JSONParser類

我用一個JSONParser類從URL獲得JSON格式的數據。這個類支持兩種http請求,GET和POST方法從URL獲取JSON數據

JSONParser.java

  1. package com.example.androidhive;  
  2.    
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.util.List;  
  9.    
  10. import org.apache.http.HttpEntity;  
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.NameValuePair;  
  13. import org.apache.http.client.ClientProtocolException;  
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  15. import org.apache.http.client.methods.HttpGet;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.client.utils.URLEncodedUtils;  
  18. import org.apache.http.impl.client.DefaultHttpClient;  
  19. import org.json.JSONException;  
  20. import org.json.JSONObject;  
  21.    
  22. import android.util.Log;  
  23.    
  24. public class JSONParser {  
  25.    
  26.     static InputStream is = null;  
  27.     static JSONObject jObj = null;  
  28.     static String json = "";  
  29.    
  30.     // constructor  
  31.     public JSONParser() {  
  32.    
  33.     }  
  34.    
  35.     // function get json from url  
  36.     // by making HTTP POST or GET mehtod  
  37.     public JSONObject makeHttpRequest(String url, String method,  
  38.             List<NameValuePair> params) {  
  39.    
  40.         // Making HTTP request  
  41.         try {  
  42.    
  43.             // check for request method  
  44.             if(method == "POST"){  
  45.                 // request method is POST  
  46.                 // defaultHttpClient  
  47.                 DefaultHttpClient httpClient = new DefaultHttpClient();  
  48.                 HttpPost httpPost = new HttpPost(url);  
  49.                 httpPost.setEntity(new UrlEncodedFormEntity(params));  
  50.    
  51.                 HttpResponse httpResponse = httpClient.execute(httpPost);  
  52.                 HttpEntity httpEntity = httpResponse.getEntity();  
  53.                 is = httpEntity.getContent();  
  54.    
  55.             }else if(method == "GET"){  
  56.                 // request method is GET  
  57.                 DefaultHttpClient httpClient = new DefaultHttpClient();  
  58.                 String paramString = URLEncodedUtils.format(params, "utf-8");  
  59.                 url += "?" + paramString;  
  60.                 HttpGet httpGet = new HttpGet(url);  
  61.    
  62.                 HttpResponse httpResponse = httpClient.execute(httpGet);  
  63.                 HttpEntity httpEntity = httpResponse.getEntity();  
  64.                 is = httpEntity.getContent();  
  65.             }             
  66.    
  67.         } catch (UnsupportedEncodingException e) {  
  68.             e.printStackTrace();  
  69.         } catch (ClientProtocolException e) {  
  70.             e.printStackTrace();  
  71.         } catch (IOException e) {  
  72.             e.printStackTrace();  
  73.         }  
  74.    
  75.         try {  
  76.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  77.                     is, "iso-8859-1"), 8);  
  78.             StringBuilder sb = new StringBuilder();  
  79.             String line = null;  
  80.             while ((line = reader.readLine()) != null) {  
  81.                 sb.append(line + "\n");  
  82.             }  
  83.             is.close();  
  84.             json = sb.toString();  
  85.         } catch (Exception e) {  
  86.             Log.e("Buffer Error""Error converting result " + e.toString());  
  87.         }  
  88.    
  89.         // try parse the string to a JSON object  
  90.         try {  
  91.             jObj = new JSONObject(json);  
  92.         } catch (JSONException e) {  
  93.             Log.e("JSON Parser""Error parsing data " + e.toString());  
  94.         }  
  95.    
  96.         // return JSON String  
  97.         return jObj;  
  98.    
  99.     }  
  100. }  
到這裏,本教程就結束了。

運行你的代碼,測試一下程序吧。你可能會遇到不少錯誤,經常使用LogCat來調試你的項目。

如果你不能解決那些錯誤,請在此留言。
原文鏈接:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

測試環境:WAMP: 2.4   Apache :2.4.4   PHP: 5.4.16

源碼下載地址: http://download.csdn.net/detail/welovesunflower/7383361

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章