Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android + JSON + PHP + MySQL 打造用戶反饋功能全流程

編輯:關於 Android 程式設計

幾乎每一個上線項目都離不開「意見反饋」這個入口。它的實現思路其實不複雜:客戶端收集用戶填寫的內容,以 POST 方式提交給服務端,服務端寫入資料庫並回傳一個 JSON 結果。下面把我在項目裡實際跑通的這套方案完整梳理一遍,供大家交流參考。

先看最終界面。表單一共三個欄位:名字與郵箱為選填,可以留空;建議內容為必填,為空時不允許提交。

一、界面布局

主布局用一個垂直方向的 LinearLayout 串起三組「標籤 + 輸入框」,底部放提交按鈕。頂部的標題列則抽成獨立文件,透過 <include> 標籤引入,這樣多個頁面可以共用同一個標題列。

<?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:text=""
        android:textColor="@color/white"
        android:textSize="18sp"
        android:shadowColor="#ff000000"
        android:shadowDx="2"
        android:shadowDy="0"
        android:shadowRadius="1"/>

    <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:background="@drawable/back"/>
</RelativeLayout>

二、客戶端邏輯

Activity 裡做三件事:初始化各個輸入框、處理返回按鈕、為提交按鈕綁定點擊事件。點擊時先做輸入校驗(建議內容不可為空),通過後再啟動 AsyncTask 在後台線程發送請求,避免阻塞 UI 線程引發 ANR。

package com.android.up;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.android.MainActivity;
import com.android.R;
import com.anroid.net.DialogUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class up extends Activity {

    private ProgressDialog pDialog;
    private TextView tv_head;
    private JSONParser jsonParser = new JSONParser();

    EditText inputName, inputEmail, inputDesc;
    Button upback;

    // 服務端接口地址,10.0.2.2 為模擬器訪問宿主機的專用地址
    private static final 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 View.OnClickListener() {
            public void onClick(View v) {
                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();
        }

        @Override
        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 {
                JSONObject json = jsonParser.makeHttpRequest(url_up, "POST", params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            pDialog.setMessage("上傳成功");
            pDialog.dismiss();
        }
    }
}

提示框工具類被封裝成靜態方法,透過 closeSelf 參數決定關閉時是否順帶結束當前 Activity:

package com.anroid.net;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.View;
import android.app.Activity;

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();
                }
            });
        } else {
            builder.setPositiveButton("確定", null);
        }
        builder.create().show();
    }

    /** 顯示一個自定義視圖 */
    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 請求、以 UTF-8 讀取回應流,最後把字串解析成 JSONObject 返回。統一在一個類裡處理編碼與異常,後續各個業務模塊都能複用。

package com.android.up;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {}

    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;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\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 接收並寫庫

服務端先判斷三個欄位是否都存在,再執行插入,最後依結果輸出不同的 JSON 回應。客戶端只要檢查返回中的 success 標識,就能判斷提交流程是否成功。

<?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"] = "寫入資料庫失敗";
    }
    echo json_encode($response);
} else {
    $response["success"] = 0;
    $response["message"] = "必填欄位缺失";
    echo json_encode($response);
}
?>

資料表結構只需 name、email、description 三個欄位即可,建立資料庫連線時記得把編碼統一設為 UTF-8,否則中文很容易出現亂碼。

至此,一個可用的用戶反饋功能就完成了,提交的內容會落到後台資料表中,後續只要在管理端做列表展示與回覆即可。

兩點實務提醒:原文的示例代碼裡,插入語句引用的是未定義的 $email 變數(實際賦值的是 $price),上線前一定要修正;另外 mysql_* 系列函數早已被廢棄,正經項目請改用 PDO 或 MySQLi 並配合預處理語句,同時在服務端做好長度與格式校驗,才能避免 SQL 注入風險。

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