Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android + JSON + PHP + MySQL 實作用戶反饋功能完整教學

編輯: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>

二、標題列 uphead.xml

包含一個標題 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>

三、Android 客戶端

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();
        }
    }
}

四、對話框工具類 DialogUtil

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();
    }
}

五、JSONParser:負責 POST 與解析

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

<?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 等情境的提示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved