Android+json+php+mysql realization of user feedback function method _android

Source: Internet
Author: User
Tags gettext http post http request xmlns
I believe that every project will have user feedback suggestions and other functions, the implementation of a lot of methods, the following is my way to achieve, for everyone to communicate. First look at the concrete interface, three fields. Name, the mailbox is optional, can be empty, the suggestion cannot be empty. If you need, you can leave a message for me.

The following is a layout code that uses a <include layout= "@layout/uphead" > is to introduce another layout file into this layout.
Copy Code code 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= "e-mail (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>

Below the Uphead layout code, which uses a TextView, a button for the return button.
Copy Code code 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 Android client code is posted below, with three classes, one for sending post requests to the server, and for JSON delivery. There is also a dailog instance.
Copy Code code 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/up.php";/here is your server-side address.
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.up);
Tv_head = (TextView) Findviewbyid (R.id.tv_head);
Tv_head.settext ("proposal");
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, "you have not filled out the proposal", 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 This 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 ("Upload success");
Pdialog.dismiss ();

}
}
}

The Dailog instance class is posted below
Copy Code code 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
{
Defines a dialog box that displays a message
public static void ShowDialog (final context CTX
, String msg, Boolean closeself)
{
Create a 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 Current Activity
(activity) CTX). Finish ();
}
});
}
Else
{
Builder.setpositivebutton ("OK", null);
}
Builder.create (). Show ();
}
Defines a dialog box that displays 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 side not much, the code is as follows
Copy Code code 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.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;
}
}

To this Android client has been completed, the server-side with Php+mysql implementation, of course, this is only an example, access to the database, no display, the code is as follows
Copy Code code 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);
}
?>

database table structure as follows, the connection database code is not posted, remember to set the code to UTF-8 on the line.


This completes a user feedback basic function, backstage data shows. Please give me a message if you have any questions.

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.