android+json+php+mysql实现用户反馈功能方法解析

2016-02-19 11:27 37 1 收藏

今天图老师小编给大家精心推荐个android+json+php+mysql实现用户反馈功能方法解析教程,一起来看看过程究竟如何进行吧!喜欢还请点个赞哦~

【 tulaoshi.com - 编程语言 】

相信每个项目都会有用户反馈建议等功能,这个实现的方法很多,下面是我实现的方法,供大家交流。首先看具体界面,三个字段。名字,邮箱为选填,可以为空,建议不能为空。如有需要可以给我留言。
 
下面贴出布局代码,这里用到一个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;
// url to create new product
private static String url_up = "http://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("建议");
// 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 AsyncTaskString, 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 price = inputEmail.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
ListNameValuePair params = new ArrayListNameValuePair();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", price));
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);
}catch(Exception e){
e.printStackTrace();
}
// check for success tag
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.setMessage("上传成功");
pDialog.dismiss();

}
}
}

下面贴出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,
ListNameValuePair 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'];
$price = $_POST['email'];
$description = $_POST['description'];
$result = mysql_query("INSERT INTO up(name, email, description) VALUES('$name', '$email', '$description')");
echo $result;
// 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就行了。


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

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

来源:https://www.tulaoshi.com/n/20160219/1597580.html

延伸阅读
近几年的前端工程师接触页面编码的时候,Table布局的时代已经没落了,取而代之的是习惯用DIV来布局组织页面架构,当然这是大势所趋。更何况HTML5+CSS3的黄金组合已经越来越被推崇!而Table只能做回老本行:去组织和展现数据信息。今天我们要谈到是CSS里的display。算是另辟蹊径来谈谈tables吧。 本文提供了简单可靠的UI布局解决方案,因为CSS t...
1、Android系统默认支持三种字体,分别为:“sans”, “serif”, “monospace 2、在Android中可以引入其他字体 。 代码如下: ?xml version="1.0" encoding="utf-8"? TableLayout xmlns:Android="http://schemas.android.com/apk/res/android"     Android:layout_width="fill_parent"     Android:layou...
标签: PHP
  作者:hutuworm 来源:糊涂馋寺 目前,不少网站为了防止用户利用机器人自动注册、登录、灌水,都采用了 验证码技术。所谓验证码,就是将一串随机产生的数字或符号,生成一幅图片, 图片里加上一些干扰象素(防止OCR),由用户肉眼识别其中的验证码信息,输 入表单提交网站验证,验证成功后才能使用某项功能。 我们这里展示...
标签: Java JAVA基础
  声明:作者原创,版权所有。未经授权,不得转载 在jsp中用bean和servlet联合实现用户注册、登录 作者:imagebear 版权:imagebear 本例需要的软件和运行环境: 1、Windows2000 Server操作系统 2、jdk1.4 3、JCreator2.5(java源码编辑调试器,吐血推荐!) 4、Macromedia JRun MX 5、Macromedia Dreamweaver MX(非必需) 6、MySQ...
1、为什么需要写一个通用xml解析方法。 当需要解析不同的xml节点。你有可能是在xml解析的时候匹配不同节点并且节点名都是写死的,这样的话你解析不同的节点就需要不同的解析方法。当然这种方式是最简单也是最笨的方法。为了减少代码把代码写得更有质量那么你就需要考虑设计一个通用的xml解析方法。 2、解析思路。 一般情况下,xml的解析结...

经验教程

282

收藏

84
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部