Android+PHP+Mysql实现用户反馈功能


在做应用程序的时候,一般都会有这样的一个需求,用来收集用户的反馈意见,下面是我实现的一种方式,主要用到的是json数据解析,Http请求,当然,服务器端使用的是开源的php技术。

下面先贴出主界面,页面布局这里就不贴出代码了,其实就是三个输入框还有一个按钮,一个返回的back按钮。


首先是实现HttpClient请求的代码:

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 or GET mehtod
	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;

	}
}



下面是实现反馈上传的代码:
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.R;
import android.app.Activity;
import android.app.ProgressDialog;
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;
import android.widget.Toast;
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;
	private static String url_up = "http://10.0.2.2/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("建议");
		tv_head.setTextSize(17);
		// 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
				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(""))
		{
			Toast.makeText(getApplicationContext(), "您还没填写建议", 5000).show();
			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("wait..");
			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
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			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);
			String message = json.getString(TAG_MESSAGE);
			return message;
		   }catch(Exception e){
			   e.printStackTrace();	
			   return "g";
		   }
		}
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String message) {			   
			pDialog.dismiss();      
			Toast.makeText(getApplicationContext(), message, 8000).show();	
		}
		}

	}



当反馈提交后,与服务器端有个交互,如果提交成功,服务器返回提交成功给客户端接收。

服务器端代码如下:

<?php
include("conn.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['description'])) {  
    $name = $_POST['name'];
    $price = $_POST['email'];
    $description = $_POST['description'];
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO up(name, email, description) VALUES('$name', '$email', '$description')");
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "  Ok  thank you ! ";
        echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "failed";     
        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值