
- Android 基礎
- Android - 首頁
- Android - 概述
- Android - 環境搭建
- Android - 架構
- Android - 應用元件
- Android - HelloWorld 示例
- Android - 資源
- Android - 活動 (Activities)
- Android - 服務 (Services)
- Android - 廣播接收器 (Broadcast Receivers)
- Android - 內容提供器 (Content Providers)
- Android - 碎片 (Fragments)
- Android - 意圖/過濾器 (Intents/Filters)
- Android - 使用者介面
- Android - UI 佈局
- Android - UI 控制元件
- Android - 事件處理
- Android - 樣式和主題
- Android - 自定義元件
- Android 高階概念
- Android - 拖放
- Android - 通知
- 基於位置的服務
- Android - 傳送郵件
- Android - 傳送簡訊
- Android - 電話呼叫
- 釋出 Android 應用
- Android 實用示例
- Android - 警報對話方塊
- Android - 動畫
- Android - 音訊捕捉
- Android - AudioManager
- Android - 自動完成
- Android - 最佳實踐
- Android - 藍牙
- Android - 相機
- Android - 剪貼簿
- Android - 自定義字型
- Android - 資料備份
- Android - 開發者工具
- Android - 模擬器
- Android - Facebook 整合
- Android - 手勢
- Android - Google 地圖
- Android - 圖片特效
- Android - ImageSwitcher
- Android - 內部儲存
- Android - JetPlayer
- Android - JSON 解析器
- Android - LinkedIn 整合
- Android - 載入動畫
- Android - 本地化
- Android - 登入介面
- Android - MediaPlayer
- Android - 多點觸控
- Android - 導航
- Android - 網路連線
- Android - NFC 指南
- Android - PHP/MySQL
- Android - 進度環
- Android - ProgressBar
- Android - 推送通知
- Android - RenderScript
- Android - RSS 閱讀器
- Android - 螢幕錄製
- Android - SDK 管理器
- Android - 感測器
- Android - 會話管理
- Android - Shared Preferences
- Android - SIP 協議
- Android - 拼寫檢查器
- Android - SQLite 資料庫
- Android - Support Library
- Android - 測試
- Android - 文字轉語音
- Android - TextureView
- Android - Twitter 整合
- Android - UI 設計
- Android - UI 模式
- Android - UI 測試
- Android - WebView 佈局
- Android - Wi-Fi
- Android - 小部件 (Widgets)
- Android - XML 解析器
- Android 實用資源
- Android - 問答
- Android - 實用資源
- Android - 討論
Android - PHP/MYSQL
本章將解釋如何將 PHP 和 MYSQL 整合到您的 Android 應用中。如果您擁有 Web 伺服器並希望訪問其資料,這將非常有用。
MYSQL 用作 Web 伺服器上的資料庫,PHP 用於從資料庫中提取資料。我們的應用程式將與 PHP 頁面通訊,並傳遞必要的引數,PHP 將連線 MYSQL 資料庫,提取結果並將其返回給我們。
PHP - MYSQL
建立資料庫
可以使用這個簡單的指令碼輕鬆建立 MYSQL 資料庫。`CREATE DATABASE` 語句建立資料庫。
<?php $con=mysqli_connect("example.com","username","password"); $sql="CREATE DATABASE my_db"; if (mysqli_query($con,$sql)) { echo "Database my_db created successfully"; } ?>
建立表
建立資料庫後,就可以在資料庫中建立一些表了。`CREATE TABLE` 語句建立資料庫表。
<?php $con=mysqli_connect("example.com","username","password","my_db"); $sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))"; if (mysqli_query($con,$sql)) { echo "Table have been created successfully"; } ?>
向表中插入值
建立資料庫和表後,現在可以向表中插入一些資料了。`INSERT INTO` 語句將資料插入表中。
<?php $con=mysqli_connect("example.com","username","password","my_db"); $sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin', 'admin','adminstrator')"; if (mysqli_query($con,$sql)) { echo "Values have been inserted successfully"; } ?>
PHP - GET 和 POST 方法
PHP 也用於在建立後從 mysql 資料庫中提取記錄。為了提取記錄,必須向 PHP 頁面傳遞有關要提取哪些記錄的資訊。
傳遞資訊的第一種方法是透過 GET 方法,其中使用 `$_GET` 命令。變數在 url 中傳遞,並提取記錄。其語法如下:
<?php $con=mysqli_connect("example.com","username","password","database name"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_GET['username']; $password = $_GET['password']; $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and Password='$password'"); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?>
第二種方法是使用 POST 方法。上述指令碼中唯一更改的是將 `$_GET` 替換為 `$_POST`。在 POST 方法中,變數不會透過 URL 傳遞。
Android - 連線 MYSQL
透過 GET 方法連線
有兩種方法可以透過 PHP 頁面連線到 MYSQL。第一種稱為 **GET 方法**。我們將使用 **HttpGet** 和 **HttpClient** 類進行連線。它們的語法如下:
URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link));
之後,您需要呼叫 HttpClient 類的 `execute` 方法,並將其接收在 HttpResponse 物件中。之後,您需要開啟流以接收資料。
HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
透過 POST 方法連線
在 POST 方法中,將使用 **URLEncoder**、**URLConnection** 類。urlencoder 將對傳遞變數的資訊進行編碼。其語法如下:
URL url = new URL(link); String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URLConnection conn = url.openConnection();
您需要做的最後一件事是將此資料寫入連結。寫入後,您需要開啟流以接收響應資料。
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
示例
以下示例是將您的 Android 應用程式與透過 PHP 頁面的 MYSQL 資料庫連線的完整示例。它建立一個基本的應用程式,允許您使用 GET 和 POST 方法登入。
PHP - MYSQL 部分
在此示例中,在 000webhost.com 上建立了一個名為 temp 的資料庫。在這個資料庫中,建立了一個名為 table1 的表。此表有三個欄位。(使用者名稱、密碼、角色)。該表只有一條記錄,即("admin","admin","administrator")。
下面給出了 php 頁面,它透過 post 方法獲取引數。
<?php $con=mysqli_connect("mysql10.000webhost.com","username","password","db_name"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; $password = $_POST['password']; $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and Password='$password'"); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?>
Android 部分
要試驗此示例,您需要在一個連線了 wifi 網路的實際裝置上執行它。
步驟 | 描述 |
---|---|
1 | 您將使用 Android Studio IDE 建立一個 Android 應用程式,並將其命名為 PHPMYSQL,包名為 com.example.phpmysql。 |
2 | 修改 src/MainActivity.java 檔案以新增 Activity 程式碼。 |
3 | 建立 src/SiginActivity.java 檔案以新增 PHPMYSQL 程式碼。 |
4 | 修改佈局 XML 檔案 res/layout/activity_main.xml,根據需要新增任何 GUI 元件。 |
5 | 修改 res/values/string.xml 檔案並新增必要的字串元件。 |
6 | 修改 AndroidManifest.xml 以新增必要的許可權。 |
7 | 執行應用程式,選擇正在執行的 Android 裝置,並在其上安裝應用程式並驗證結果。 |
以下是 **src/com.example.phpmysql/MainActivity.java** 的內容。
package com.example.phpmysql; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText usernameField,passwordField; private TextView status,role,method; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usernameField = (EditText)findViewById(R.id.editText1); passwordField = (EditText)findViewById(R.id.editText2); status = (TextView)findViewById(R.id.textView6); role = (TextView)findViewById(R.id.textView7); method = (TextView)findViewById(R.id.textView9); } public void login(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText("Get Method"); new SigninActivity(this,status,role,0).execute(username,password); } public void loginPost(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText("Post Method"); new SigninActivity(this,status,role,1).execute(username,password); } }
以下是 **src/com.example.phpmysql/SigninActivity.java** 的內容。
package com.example.phpmysql; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.os.AsyncTask; import android.widget.TextView; public class SigninActivity extends AsyncTask{ private TextView statusField,roleField; private Context context; private int byGetOrPost = 0; //flag 0 means get and 1 means post.(By default it is get.) public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) { this.context = context; this.statusField = statusField; this.roleField = roleField; byGetOrPost = flag; } protected void onPreExecute(){ } @Override protected String doInBackground(String... arg0) { if(byGetOrPost == 0){ //means by Get Method try{ String username = (String)arg0[0]; String password = (String)arg0[1]; String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line=""; while ((line = in.readLine()) != null) { sb.append(line); break; } in.close(); return sb.toString(); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } else{ try{ String username = (String)arg0[0]; String password = (String)arg0[1]; String link="http://myphpmysqlweb.hostei.com/loginpost.php"; String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL(link); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); wr.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while((line = reader.readLine()) != null) { sb.append(line); break; } return sb.toString(); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } } @Override protected void onPostExecute(String result){ this.statusField.setText("Login Successful"); this.roleField.setText(result); } }
將以下內容新增到 **build.gradle** 並重新構建整個專案。
android { useLibrary 'org.apache.http.legacy' }
以下是 **activity_main.xml** 的內容。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="25dp" android:ems="10" android:inputType="textPassword" > </EditText> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="44dp" android:ems="10" > <requestFocus android:layout_width="wrap_content" /> </EditText> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" android:text="@string/Username" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="@string/App" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView5" android:layout_alignLeft="@+id/textView6" android:text="@string/Role" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView6" android:layout_marginTop="27dp" android:layout_toLeftOf="@+id/editText1" android:text="@string/LoginRole" /> <TextView android:id="@+id/textView8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView6" android:layout_alignLeft="@+id/textView5" android:layout_marginBottom="27dp" android:text="@string/method" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView8" android:layout_below="@+id/button1" android:layout_marginTop="86dp" android:text="@string/LoginStatus" /> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView4" android:layout_centerHorizontal="true" android:text="@string/Status" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <TextView android:id="@+id/textView9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView8" android:layout_alignLeft="@+id/textView6" android:text="@string/Choose" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/textView6" android:onClick="loginPost" android:text="@string/LoginPost" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_alignLeft="@+id/textView2" android:onClick="login" android:text="@string/LoginGet" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2" android:layout_alignParentLeft="true" android:text="@string/Password" /> </RelativeLayout>
以下是 **strings.xml** 的內容。
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">PHPMYSQL</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="Username">Username</string> <string name="Password">Password</string> <string name="LoginGet">Login - Get</string> <string name="LoginPost">Login - Post</string> <string name="App">Login Application</string> <string name="LoginStatus">Login Status</string> <string name="LoginRole">Login Role</string> <string name="Status">Not login</string> <string name="Role">Not assigned</string> <string name="method">Login Method</string> <string name="Choose">Choose Method</string> </resources>
以下是 **AndroidManifest.xml** 的內容。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.phpmysql" > <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.phpmysql.MainActivity" 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> </manifest>
讓我們嘗試執行您的 PHPMYSQL 應用程式。我假設您已將實際的 Android 手機裝置連線到您的計算機。要在 Android Studio 中執行該應用程式,請開啟專案的一個 activity 檔案,然後單擊工具欄中的執行 圖示。在啟動應用程式之前,Android Studio 將顯示以下視窗,讓您選擇要在其中執行 Android 應用程式的選項。

選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示以下螢幕:

現在只需輸入您的使用者名稱和密碼。在我的例子中,我輸入 admin 作為使用者名稱和密碼。如圖所示:

現在按“Get”按鈕,等待幾秒鐘,響應將被下載並顯示給您。在這種情況下,響應是在使用者名稱和密碼為 admin 時獲取的 ROLE。如下圖所示:

現在再次按下“POST”按鈕,將出現相同的結果。如下圖所示:
