編輯:關於 Android 程式設計
上一篇講了讀取,這篇來談寫入。Android 把本地資料(例如定位、感測器讀數)上傳到資料庫,流程是:把參數封裝成 POST 表單 → 送到 PHP → PHP 寫入 MySQL 並回傳結果。
把 HTTP POST 的細節收在一個類別裡,主程式只要呼叫一行就能完成上傳:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url by making HTTP POST
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// request method is POST
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
Log.d("json", json.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
注意建表單時明確指定了 HTTP.UTF_8,這是避免中文欄位上傳後變亂碼的關鍵。
params = new ArrayList<NameValuePair>();
// 這裡可以替換成你自己程式中的一些鍵值對
params.add(new BasicNameValuePair("time", "" + time));
params.add(new BasicNameValuePair("lat", "" + lat));
params.add(new BasicNameValuePair("lon", "" + lon));
params.add(new BasicNameValuePair("encyptiontype", encyptiontype));
params.add(new BasicNameValuePair("rssi", rssi));
params.add(new BasicNameValuePair("name", name));
JSONParser jsonParser = new JSONParser();
// 數據的 php 文件的路徑
String url_up = "******/文件名字.php";
try {
JSONObject json = jsonParser.makeHttpRequest(url_up, "POST", params);
Log.v("uploadsucceed", "uploadsucceed");
} catch (Exception e) {
e.printStackTrace();
}
<?php
// array for JSON response
// 此處需要將數據庫名、表名還有密碼做相應修改,改成你自己的
$con = mysql_connect("localhost", "root", null);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a0722152915", $con);
$response = array();
include("conn.php");
// check for required fields
if (isset($_POST['time']) && isset($_POST['lat']) && isset($_POST['lon'])
&& isset($_POST['encyptiontype']) && isset($_POST['rssi']) && isset($_POST['name'])) {
$time = $_POST['time'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$encyptiontype = $_POST['encyptiontype'];
$rssi = $_POST['rssi'];
$name = $_POST['name'];
$result = mysql_query("INSERT INTO wifi_state(time, lat, lon, encyptiontype, rssi, name)
VALUES('$time', '$lat', '$lon', '$encyptiontype', '$rssi', '$name')");
echo $result;
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
回傳一個帶有 success 與 message 的 JSON,Android 端就能明確知道寫入成功與否,而不是只能盲等。
如果你的裝置是 Android 4.0 以上,需要加上這段程式碼,否則網路請求會直接拋出例外:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
// or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
4.0 以下的系統則不需要這段。不過要提醒的是,StrictMode 的設計初衷是幫助你找出問題,而不是用來「關掉警告」。正式專案請把網路請求移到背景執行緒(AsyncTask、執行緒池或 Kotlin 協程),而不是靠 penaltyLog() 把例外吞掉。

把這份範例落進真實專案前,請確認以下幾件事:
VALUES('$time', '$lat', ...) 這種寫法完全沒有防禦 SQL Injection,任何能攔截到這個請求的人都能對你的資料庫下達任意指令。curl 灌入假資料。mysqli 並設定 utf8mb4。才能正確處理 emoji 與罕用漢字。讀取方向的實作請參考姊妹篇。兩篇合起來,就是 Android 與 MySQL 透過 JSON 溝通最基礎的完整拼圖;掌握這個骨架之後,替換成 Retrofit 或任何現代框架都只是形式上的調整。
Material Design 圖片處理指南:染色、取色與向量圖
向量圖放大不失真,單色 app icon 更是它的拿手場景;同一張圖片還能透過 alpha 與執行期上色,靈活套用不同主題。而若想讓介面配色與內容保持一致,還能直接從圖片
Android 透過廣播異步更新 UI 與 ANR 排查
範例目標 這個範例模擬透過廣播觸發背景工作,再回到主執行緒更新 UI。畫面中有一個 TextView 與一個按鈕,點擊按鈕後送出自訂廣播,BroadcastReceive
Android 創建與引用 Library Project(庫項目)完整教程
開發過程中,为了实现某個陌生的效果或功能,我們常常會求助於網上優秀的開源項目。使用時會發現,引用開源的 Library Project(庫項目)確實能解決不少問題,也提供
TRIM:提升磁盤性能,緩解 Android 卡頓
在業內,Android 手機一直有著「越用越慢」的口碑。根據第三方調研數據,有 77% 的 Android 手機用戶承認曾遭遇過手機變慢的困擾。他們不明白,為什麼購買之初