The example in this article describes how Android writes data to MySQL via JSON. Share to everyone for your reference, specific as follows:
Let's talk about how to upload data from the Android program to MySQL via JSON:
First define a class Jsonparser.java class, the JSON upload data method encapsulation, you can directly in the main program call the class, the code is as follows
public class Jsonparser {static InputStream = null; static jsonobject jobj = null; static String JSON = ""; Constructor public Jsonparser () {}/function get JSON to URL//by making HTTP POST public jsonobject makehttprequ
EST (string url, string method, list<namevaluepair> params) {//making HTTP Request try {//Request # 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 (i
S, "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 Pars
Er "," Error parsing data "+ e.tostring ());}
Return JSON String return jobj;
}
}
This is called in the main program:
params = new arraylist<namevaluepair> ();
Here you can replace some of the key values in your own program to
Params.add (new Basicnamevaluepair ("Time", "+time");
Params.add (New Basicnamevaluepair ("Lat", "" +lat));
Params.add (New Basicnamevaluepair ("Lon", "" +lon));
Params.add (New Basicnamevaluepair ("Encyptiontype", Encyptiontype));
Params.add (New Basicnamevaluepair ("Rssi", Rssi));
Params.add (New Basicnamevaluepair ("name", name));
Jsonparser jsonparser = new Jsonparser ();
The path to the PHP file for the data
String url_up = "******/file name. php";
try{
Jsonobject json = jsonparser.makehttprequest (url_up, "POST", params);
LOG.V ("Uploadsucceed", "uploadsucceed");
} catch (Exception e) {
e.printstacktrace ();
}
The last is to define a PHP file that receives data:
<?php//array for JSON response//Here you need to change the database name and the password to make the corresponding changes to your own $con = mysql_connect ("localhost", "root", null);
if (! $con) {die (' could not connect: '. Mysql_error ());} mysql_select_db ("a0722152915", $con);
$response = Array ();
Include ("conn.php"); Check for required fields if (isset [$_post[' time ']) && isset ($_post[' lat ']) && isset ($_post[' lon ']) & amp;& isset ($_post[' Encyptiontype ']) && isset ($_post[' Rssi ']) && isset ($_post[' name ')) {$time = $
_post[' time '];
$lat = $_post[' lat '];
$lon = $_post[' lon '];
$encyptiontype = $_post[' Encyptiontype '];
$rssi = $_post[' Rssi '];
$name = $_post[' name ']; $result = mysql_query (INSERT into Wifi_state (time, lat, lon,encyptiontype,rssi,name) VALUES (' $time ', ' $lat ', ' $lon ', ' $
Encyptiontype ', ' $rssi ', ' $name ');
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);
}?>
Note: If your device has an Android operating system of more than 4.0, then add the following code to the main program to upload the successful
Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder ()
. Detectdiskreads ()
. Detectdiskwrites ()
. Detectnetwork ()//or. Detectall () to all detectable problems
. Penaltylog ()
. Build ());
Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder ()
. Detectleakedsqlliteobjects ()
. Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). Build
());
If it's the operating system under 4.0, of course not.
The following is the successful upload effect chart:
The method of reading the data is presented in the next "read a chapter" on the way Android reads and writes data to MySQL via JSON.
For more information on Android-related content readers can view the site: "The Android operation JSON format Data Skills summary", "Android Database Operating skills summary", "Android Programming activity Operating Skills summary", " Android File Operation Tips Summary, "Android programming development of the SD card operation method Summary", "Android Development introduction and Advanced Course", "Android Resource Operation skills Summary", "Android View tips Summary" and " A summary of the usage of Android controls
I hope this article will help you with the Android program.