Android 通過PHP連接Mysql

1. 通過 MySQL在windows下的配置 中介紹第二種方法,在服務器機器上配置php和mysql環境,譬如我的服務器機器ip爲:10.141.249.136

2. 新建在test數據庫下新建一個teacher表,表的內容如下:

Android通過PHP連接MySQL(讀取)

3. 在服務器機器上的phpnow安裝目錄E:\PHPnow-1.5.5\htdocs下新建一個test.php文件,文件內容如下:

<?php
$link=mysql_connect("127.0.0.1","root","123456");
mysql_query("SET NAMES utf8");
mysql_select_db("test",$link);
$sql=mysql_query("select * from teacher ",$link);
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

4. 新建一個Android Java Project
需要修改的是一下三個文件:AndroidTestActivity.java、main.xml、AndroidManifest.xml
//AndroidTestActivity.java
package com.knight.android.test;//根據實際的工程需要,修改包的名稱

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

import android.app.Activity;

import android.net.ParseException;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

 

public class AndroidTestActivity extends Activity {

    JSONArray jArray;

    String result = null;

    InputStream is = null;

    StringBuilder sb = null;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       Button b1 = (Button) findViewById(R.id.button1);

       b1.setOnClickListener(new Button.OnClickListener() {

           @Override

           public void onClick(View v) {

              // TODO Auto-generated method stub

              EditText tv = (EditText) findViewById(R.id.editView);

              ArrayList<NameValuePair> nameValuePairs = newArrayList<NameValuePair>();

              // http get

              try {

                  HttpClient httpclient = new DefaultHttpClient();

                  HttpGet httpget = new HttpGet(

                         "http://10.141.249.136/test.php");

                  HttpResponse response = httpclient.execute(httpget);

                  HttpEntity entity = response.getEntity();

                  is = entity.getContent();

              } catch (Exception e) {

                  Log.e("log_tag", "Error in http connection" + e.toString());

              }

              // convert response to string

              try {

                  BufferedReader reader = new BufferedReader(

                         new InputStreamReader(is, "iso-8859-1"), 8);

                  sb = new StringBuilder();

                  sb.append(reader.readLine() + "\n");

 

                  String line = "0";

                  while ((line = reader.readLine()) != null) {

                     sb.append(line + "\n");

                  }

                  is.close();

                  result = sb.toString();

              } catch (Exception e) {

                  Log.e("log_tag", "Error converting result " + e.toString());

              }

              // paring data

              int ct_id;

              String ct_name;

              try {

                  jArray = new JSONArray(result);

                  JSONObject json_data = null;

                  for (int i = 0; i < jArray.length(); i++) {

                     json_data = jArray.getJSONObject(i);

                     ct_id = json_data.getInt("id");

                     ct_name = json_data.getString("name");

                     tv.append(ct_name + " \n");

                  }

              } catch (JSONException e1) {

                  // Toast.makeText(getBaseContext(), "No City Found"

                  // ,Toast.LENGTH_LONG).show();

              } catch (ParseException e1) {

                  e1.printStackTrace();

              }

           }

       });

    }

}

 


layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click" />

    <EditText
        android:id="@+id/editView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HI "
        android:textSize="30dip" />

</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.knight.android.test"
    android:versionCode="1"
    android:versionName="1.0" >
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    <!-- 授權訪問網絡 -->
<uses-permission android:name="android.permission.INTERNET"/>

</manifest>

5. 運行結果如下圖:
Android通過PHP連接MySQL(讀取)

點擊click以後,Android會向服務器發送一個Http Get請求,服務器從mysql中讀取數據後,傳送給Android客戶端,客戶端編碼數據包,然後返回如下結果:

Android通過PHP連接MySQL(讀取)


注意:
(1)AndroidManifest.xml中不能出現<uses-sdk android:minSdkVersion="15" />這種屬性,否則Android客戶端無法連接到遠程服務器
(2)如果在本機搭建mysql和php環境,以上程序(AndroidTestActivity.java)中紅色部分應更改爲:
HttpGet httpget = new HttpGet("http://10.0.2.2/test.php");
    127.0.0.1表示手機的本機ip,因爲程序最終是在手機上跑的
(3)如果讀者自定義的工程,需要修改一下幾個地方:
  • 第一個是 AndroidTestActivity.java 程序裏面的package名稱package com.knight.android.test;這個根據讀者自己定義的包要做出相應的修改(綠色部分)
  • 第二個是修改 AndroidManifest.xml裏面第三行的package=" com.knight.android.test",要保持綠色部分和第一條中的綠色部分相對應
  • 第三點是修改AndroidManifest.xml裏面activity下面的 android:name=". AndroidTestActivity",將綠色部分修改爲 AndroidTestActivity.java的紅色部分(也就是類名)
(4)在MySQL中把編碼設置成utf8_unicode_ci,在瀏覽器中輸入:localhost/test.php,如果中文出現亂碼,可以把輸出的內容複製到http://tools.jb51.net/tools/json/json_editor.htm,如果在這裏能顯示正常,則說明實際上是的對的,因爲瀏覽器輸出的是json編碼
(5)更多內容還可以參考: http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/ ,這個網站中部分內容是錯的,擇其善者而從之

轉載:http://www.baidu.com/link?url=gYXQsjBgesFOCm3tE114BboK4_Z0ruVgapDvlBcu9Ds0sUfclNbSm3RLeiTWE5qURBLCNAYLVPat5MZW7N_jjK
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章