您的位置:首页 > 移动开发 > Android开发

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

2012-12-18 13:47 796 查看
在做应用程序的时候,一般都会有这样的一个需求,用来收集用户的反馈意见,下面是我实现的一种方式,主要用到的是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 = "";// constructorpublic JSONParser() {}// function get json from url// by making HTTP POST or GET mehtodpublic JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {// Making HTTP requesttry {// request method is POST// defaultHttpClientDefaultHttpClient 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 objecttry {jObj = new JSONObject(json);} catch (JSONException e) {Log.e("JSON Parser", "Error parsing data " + e.toString());}// return JSON Stringreturn 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 Dialogprivate 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";@Overridepublic 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 TextinputName = (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() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubup.this.finish();}});// Create buttonButton btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);// button click eventbtnCreateProduct.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {// creating new product in background threadif(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* */@Overrideprotected 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 ParametersList<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 methodtry{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();}}}
当反馈提交后,与服务器端有个交互,如果提交成功,服务器返回提交成功给客户端接收。
服务器端代码如下:<?phpinclude("conn.php");// array for JSON response$response = array();// check for required fieldsif (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);}?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android MYSQL Php