Android + json + php + mysql: analysis of user feedback Functions

Source: Internet
Author: User

I believe that every project will have user feedback and other functions. There are many implementation methods. The following are my implementation methods for your communication. First, let's look at the specific interface with three fields. Name. the email address is optional. It can be blank. We recommend that you do not enter it. Leave a message if necessary.

The following is the layout code. Here, a <include layout = "@ layout/uphead"> is used to introduce another layout file to the layout. Copy codeThe Code is as follows: <? 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 = "Name (optional )"
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 = "email (optional )"
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 = "recommended (required )"
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 = "Submit"
Android: textSize = "20sp"
Android: textColor = "@ color/coffee"
/>
</LinearLayout>

The following is the layout code of uphead, which uses a TextView and a Button as the return Button.Copy codeThe Code is as follows: <? 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>

The following is the android client code. There are three classes: one for sending post requests and json transmission in interaction with the server. There is also a Dailog instance.Copy codeThe Code is as follows: 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. php"; // enter the address of your server.
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. up );
TV _head = (TextView) findViewById (R. id. TV _head );
TV _head.setText ("recommended ");
// 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(cmd.exe cute ();
}
}
});
}
Private boolean validate ()
{
String description = inputDesc. getText (). toString (). trim ();
If (description. equals (""))
{
DialogUtil. showDialog (this, "you have not filled in the suggestion", 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 ("Uploading ..");
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 );
} 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 ("uploaded successfully ");
PDialog. dismiss ();

}
}
}

The following is a Dailog instance classCopy codeThe Code is as follows :/**
*
*/
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
{
// Define a message display dialog box
Public static void showDialog (final Context ctx
, String msg, boolean closeSelf)
{
// Create an AlertDialog. Builder object
AlertDialog. Builder builder = new AlertDialog. Builder (ctx)
. SetMessage (msg). setCancelable (false );
If (closeSelf)
{
Builder. setPositiveButton ("OK", new OnClickListener ()
{
Public void onClick (DialogInterface dialog, int which)
{
// End the current Activity
(Activity) ctx). finish ();
}
});
}
Else
{
Builder. setPositiveButton ("OK", null );
}
Builder. create (). show ();
}
// Define a dialog box to display the specified component
Public static void showDialog (Context ctx, View view)
{
AlertDialog. Builder builder = new AlertDialog. Builder (ctx)
. SetView (view). setCancelable (false)
. SetPositiveButton ("OK", null );
Builder. create ()
. Show ();
}
}

The rest is how to interact with the server. The Code is as follows:Copy codeThe Code is as follows: 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.exe cute (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;
}
}

By now, the android client has been completed, and the server is implemented using php + mysql the day after tomorrow. Of course, this is only an instance. It is accessed to the database and is not displayed. The Code is as follows:Copy codeThe Code is as follows: <? 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 );
}
?>

The database table structure is as follows, the database connection code will not be pasted out, remember to set the encoding to UTF-8 on the line.


This completes a basic user feedback function, which is displayed in the background data. If you have any questions, please leave a message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.