PHP对接

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

链接:http://blog.csdn.net/welovesunflower/article/details/7776438

http://blog.csdn.net/davidluo001/article/details/42460167

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值