編輯:Android 開發實例
幾乎每個 App 都需要「意見反饋」入口。本文示範一條完整的資料流:Android 客戶端表單 → POST + JSON → PHP 寫入 MySQL。

介面共三個欄位:名字與郵箱為選填,可以留空;建議內容必填。
這裡用 <include layout="@layout/uphead"/> 把另一個布局檔合併進來,讓標題列可以重複使用。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/bg_gray">
<include layout="@layout/uphead"/>
<!-- 名字 -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="名字(選填)"
android:paddingLeft="10dip" android:paddingRight="10dip"
android:paddingTop="10dip"
android:textColor="@color/coffee" android:textSize="12sp"/>
<EditText android:id="@+id/inputName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- 郵箱 -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="郵箱(選填)"
android:paddingLeft="10dip" android:paddingRight="10dip"
android:paddingTop="10dip"
android:textColor="@color/coffee" android:textSize="12sp"/>
<EditText android:id="@+id/inputEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- 建議內容 -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="建議(必填)"
android:paddingLeft="10dip" android:paddingRight="10dip"
android:paddingTop="10dip"
android:textColor="@color/coffee" android:textSize="12sp"/>
<EditText android:id="@+id/inputDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:lines="4"
android:gravity="top"/>
<Button android:id="@+id/btnCreateProduct"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="提交"
android:textSize="20sp"
android:textColor="@color/coffee" />
</LinearLayout>
包含一個標題 TextView 與一個返回按鈕。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/top">
<TextView android:id="@+id/tv_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:shadowColor="#ff000000"
android:shadowDx="2" android:shadowDy="0" android:shadowRadius="1"
android:textColor="@color/white" android:textSize="18sp" />
<Button android:id="@+id/upback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="17dp"
android:drawableLeft="@id/tv_head"
android:background="@drawable/back" />
</RelativeLayout>
public class up extends Activity {
private ProgressDialog pDialog;
private TextView tv_head;
JSONParser jsonParser = new JSONParser();
EditText inputName, inputEmail, inputDesc;
Button upback;
// 伺服器端位址(模擬器用 10.0.2.2 指向本機)
private static String url_up = "https://10.0.2.2/up/up.php";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.up);
tv_head = (TextView) findViewById(R.id.tv_head);
tv_head.setText("建議");
inputName = (EditText) findViewById(R.id.inputName);
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputDesc = (EditText) findViewById(R.id.inputDesc);
upback = (Button) findViewById(R.id.upback);
upback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent back = new Intent(up.this, MainActivity.class);
back.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(back);
up.this.finish();
}
});
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (validate()) { // 驗證通過才送出
new Up().execute();
}
}
});
}
// 建議內容為必填
private boolean validate() {
String description = inputDesc.getText().toString().trim();
if (description.equals("")) {
DialogUtil.showDialog(this, "您還沒有填寫建議", false);
return false;
}
return true;
}
class Up extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(up.this);
pDialog.setMessage("正在上傳..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
String description = inputDesc.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("description", description));
try {
// 此介面接受 POST 方法
JSONObject json = jsonParser.makeHttpRequest(url_up, "POST", params);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.setMessage("上傳成功");
pDialog.dismiss();
}
}
}
public class DialogUtil {
// 顯示純文字訊息對話框
public static void showDialog(final Context ctx, String msg, boolean closeSelf) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setMessage(msg).setCancelable(false);
if (closeSelf) {
builder.setPositiveButton("確定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((Activity) ctx).finish(); // 順便結束當前 Activity
}
});
} else {
builder.setPositiveButton("確定", null);
}
builder.create().show();
}
// 顯示帶自訂 View 的對話框
public static void showDialog(Context ctx, View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setView(view).setCancelable(false)
.setPositiveButton("確定", null);
builder.create().show();
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
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());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
<?php
$response = array();
include("conn.php"); // 資料庫連線
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['description'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$description = $_POST['description'];
$result = mysql_query("INSERT INTO up(name, email, description)
VALUES('$name', '$email', '$description')");
if ($result) {
$response["success"] = 1;
$response["message"] = "意見回饋提交成功。";
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
資料表結構如下,連線程式碼這裡不再贅述,只要記得把編碼設為 UTF-8 即可,避免中文變亂碼。

這份範例聚焦在流程打通,因此 PHP 端直接採用字串拼接 SQL,實際上線時請務必改用參數化查詢(如 PDO prepared statement)並加上伺服器端欄位驗證,否則會留下 SQL Injection 風險。Android 端也應補上網路失敗、伺服器回傳 success=0 等情境的提示。
Android 登入頁面 from scratch:輸入欄位、錯誤提示到次數鎖定
登入頁面是所有需要帳號的 App 都躲不掉的一關。它看起來只是兩個輸入框加一顆按鈕,實際上要顧的事情不少:密碼欄必須遮蔽輸入、按鈕要綁定事件、錯誤時要給明確回饋,還得有一
Android 登入畫面實作:輸入欄位與失敗次數鎖定
登入畫面幾乎是每個需要帳號服務的應用都會遇到的題目——不論是自家服務,還是透過 Facebook、微博等第三方帳號授權。一個稱職的登入介面除了「能登入」,還必須處理好密碼
修正圖片方向:讀取 EXIF 資訊並自動旋轉顯示
用 ImageView 顯示從相機或網路取得的照片時,常會遇到一個惱人的狀況:圖是對的,方向卻歪了,甚至有時候整個倒過來。這不是你的 Bitmap 出了問題,而是方向資訊
Android ListView 圓角外觀實作技巧
若希望 ListView 呈現圓角或對話框式外觀,可以透過背景資源快速實現。 實作方式 在 ListView 上設定 android:background 屬性,並指定