android+json+php+mysql实现用户反馈功能

相信每个项目都会有用户反馈建议等功能,这个实现的方法很多,下面是我实现的方法,供大家交流。首先看具体界面,三个字段。名字,邮箱为选填,可以为空,建议不能为空。如有需要可以给我留言。

下面贴出布局代码,这里用到一个<include layout="@layout/uphead">就是把另外一个布局文件引入到这个布局中。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://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"/>

    <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="名字(选填)"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:textColor="@color/coffee"
        android:paddingTop="10dip"
        android:textSize="12sp"/>

    <!-- Input Name -->
    <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"/>

    <!-- Price Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="邮箱(选填)"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:textColor="@color/coffee"
        android:paddingTop="10dip"
        android:textSize="12sp"/>

    <!-- Input Price -->
    <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"/>

    <!-- Description Label -->
    <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"/>

    <!-- Input description -->
    <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 Create Product -->
    <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的布局代码,里面用到一个TextView,一个Button为返回按钮。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://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:text=""
            android:textColor="@color/white"
            android:textSize="18sp"
            android:textStyle="bold" />
        <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客户端代码,三个类,一个用于与服务器交互发送post请求,以及json的传递。还有一个Dailog实例。

package com.android.up;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class up extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    private TextView tv_head;
    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputEmail;
    EditText inputDesc;
    Button upback;

    // 定义脚本文件地址,我这里是本地搭建的地址,服务器段脚本文件名为up.php
    private static String url_up = "http://127.0.0.1/up/up.php";
    private static final String TAG_MESSAGE = "message";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.up);
        tv_head = (TextView)findViewById(R.id.tv_head);
        tv_head.setText("建议");
        // Edit Text
        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) {
                // TODO Auto-generated method stub
                Intent back = new Intent(up.this,MainActivity.class);
                back.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(back);
                up.this.finish();
            }
        });

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                // creating new product in background thread
                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;
    }
    /**
     * Background Async Task to Create new product
     * */
    class Up extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(up.this);
            pDialog.setMessage("正在上传..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String email = inputEmail.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
           try{
            JSONObject json = jsonParser.makeHttpRequest(url_up,
                    "POST", params);
            String message = json.getString(TAG_MESSAGE);
            return message;
           }catch(Exception e){
               e.printStackTrace();
               return "";
           }
            // check for success tag

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String message) {
            pDialog.dismiss();
           //message 为接收doInbackground的返回值
            Toast.makeText(getApplicationContext(), message, 8000).show();    

        }
        }

    }

下面贴出Dailog实例类

/**
 *
 */
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对象
        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
                    ((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();
    }
}

剩下就是如何与服务器端交互了不多说,代码如下

package com.android.up;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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 = "";
    // 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
                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;

    }
}

到此android客户端已经完成,后天服务器端用php+mysql实现,当然这里只是个实例,存取到数据库里面,没有进行展示,代码如下

<?php
// array for JSON response
$response = array();
include("conn.php");
// check for required fields
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‘)");// check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

数据库表结构如下,连接数据库代码就不贴出了,记得把编码设置为UTF-8就行了。

到此就完成了一个用户反馈的基本功能,后台数据里展示。如有问题欢迎给我留言。

【原文地址】:http://www.cnblogs.com/LIANQQ/archive/2012/11/14/2769911.html

时间: 2024-08-29 03:20:39

android+json+php+mysql实现用户反馈功能的相关文章

使用SAE的服务来实现android端的用户反馈功能。

这篇是上个月在SAE论坛上写的,现在也转过来吧. 因为应用的需要在SAE开了个jvm来帮android端合并一些请求,提供一些查询和抓取服务.但是SAE的jvm比较贵,每个小时都要5云豆,所以就打算搞点其他的功能,搭建一个简单的服务端,根据需要添加其他功能. 首先想到写个用户反馈的功能,这里需要先在SAE应用里建立一个MySQL数据库,具体创建可以参考SAE的文档. 先是Android端提交数据的代码: 1 public class UserMessage extends Activity im

Android开发之JavaMail发送邮件(用户反馈)

给APP增加了一个用户反馈的小功能,由于懒的搭服务器,所以就用邮件的形式进行通信,有如下两种方式: 1.使用调用手机上的其他程序完成邮件发送 2.使用javamail进行邮件发送 这里果断使用javamail,因为我们大多数并不会在手机上使用邮件APP 使用javamail需要三个jar包,分别是additional.jar.mail.jar和activation.jar,可以到google官网下载:https://code.google.com/archive/p/javamail-andro

iOS:移动端“用户反馈和客服”的几个平台SDK的介绍

简单阐述: 用户反馈功能几乎是每个app都有的一个功能点,通过反馈功能实现与用户的连接.沟通,随时随地收集用户意见反馈和Bug报告,即时和用户保持沟通,在一定程度上提升了app的竞争力.而给app评分也是一个常见的功能.在目前的技术实现中,有那么几个平台SDK可供使用,分别是:网易七鱼.Bugtags.Instabug.微客服.环信客服.融云客服.阿里百川等. 平台SDK: 1.网易七鱼: 介绍: 无缝融合多渠道 在线客服.呼叫中心.客服机器人.工单系统,由表及里全面打造高效的客户服务体系. 文

友盟用户反馈自定义UI-Android

友盟用户反馈SDK是友盟为开发者提供的组件之一,用户反馈也是每款应用必不可少的模块.如果你想方便的收集用户的反馈建议,并且与发送反馈的用户进行沟通交流,那么友盟用户反馈SDK是你不错的选择,使用友盟用户反馈SDK两行代码实现开发者和用户轻松高效沟通.从友盟BBS看到许多开发者都希望通过自定义UI,来实现用户反馈功能.下面就为大家来讲解如何使用友盟用户反馈SDK来制定UI.这里以一个demo来说明. 首先上图,这是自定义的UI界面: 注:部分资源文件来源于某开源App 使用友盟用户反馈的数据接口,

Android NDK开发(八)——应用监听自身卸载,弹出用户反馈调查

转载请注明出处:http://blog.csdn.net/allen315410/article/details/42521251 监听卸载情景和原理分析 1,情景分析 在上上篇博客中我写了一下NDK开发实践项目,使用开源的LAME库转码MP3,作为前面几篇基础博客的加深理解使用的,但是这样的项目用处不大,除了练练NDK功底.这篇博客,我将讲述一下一个各大应用中很常见的一个功能,同样也是基于JNI开发的Android应用小Demo,看完这个之后,不仅可以加深对NDK开发的理解,而且该Demo也可

MySQL实现排名并查询指定用户排名功能,并列排名功能

MySQL实现排名并查询指定用户排名功能,并列排名功能 表结构: CREATE TABLE test.testsort ( id int(11) NOT NULL AUTO_INCREMENT, uid int(11) DEFAULT 0 COMMENT '用户id', score decimal(10, 2) DEFAULT 0.00 COMMENT '分数', PRIMARY KEY (id) ) ENGINE = INNODB AUTO_INCREMENT = 1 CHARACTER SE

使用SAE的Storage来为Android应用提供版本更新的检查和下载功能

因为Android的市场比较分散,有时候上传和审核都麻烦.为了让用户能第一时间获得更新,接下来要实现版本检查和下载功能.先在Storage里放入应用的APK.一个json的文档或者xml文件,因为我比较喜欢用json,所以接下来就用json文档.写json文档的时候记得不要用记事本,要用Notepad++之类的文本编辑器来写,然后保存成UTF-8无BOM的格式.不然android4.0以下版本解析会有问题.更新数据的格式:{      "version": 10,      "

如何让你的用户反馈更简单

有用户问题我,什么时候推出像知乎 iOS 客户端那样面向普通用户的摇一摇反馈功能,其实通过 Bugtags 的提供的接口完全可以自主实现这个功能,而且非常简单. 下图是知乎 iOS 客户端摇一摇后弹出的反馈提示 点击遇到问题,就会自动截屏,然后用户就可以提交问题啦. 那么怎么通过 Bugtags 来实现这样的用户反馈呢?这里就需要用到 Bugtags 的手动调用接口: /** * 手动调用截屏界面 * @return none */ + (void)invoke; 我们只需获取应用的摇一摇事件,

集成友盟的意见反馈功能

最近一直在开发毕业设计的项目,其中用到了很多自己没接触过的东西,就包括集成友盟SDK的意见反馈模块的内容了.确实用了一点心思在里面,捣鼓了一阵子,中间也遇到了一些问题,关键这问题也不好解决,问大神大神也不一定有去接触这一块,然后网上是有很多资料,但总感觉对我的帮助不是很大,所以,当完成了友盟的这块功能后,就特别想贡献出来,一是为以后方便自己重温这块知识点,二是顺便 发布出来帮助像我这样遇到问题一直寻求解决办法的人.好了,废话不多说了,直接上效果图,然后PO代码! 效果图如下: 当然顺便也po上友