Android通过json向MySQL中读写数据的方法详解【写入篇】
程序员文章站
2024-03-04 22:58:18
本文实例讲述了android通过json向mysql中写入数据的方法。分享给大家供大家参考,具体如下:
先说一下如何通过json将android程序中的数据上传到mysq...
本文实例讲述了android通过json向mysql中写入数据的方法。分享给大家供大家参考,具体如下:
先说一下如何通过json将android程序中的数据上传到mysql中:
首先定义一个类jsonparser.java类,将json上传数据的方法封装好,可以直接在主程序中调用该类,代码如下
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; } }
主程序中这样调用:
params = new arraylist<namevaluepair>(); //这里可以替换成你自己程序中的一些键值对 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(); //数据的php文件的路径 string url_up = "******/文件名字.php"; try{ jsonobject json = jsonparser.makehttprequest(url_up,"post", params); log.v("uploadsucceed", "uploadsucceed"); }catch(exception e){ e.printstacktrace(); }
最后就是定义一个接收数据的php文件:
<?php // array for json response //此处需要将数据库名和表明还有密码做相应修改,改成你自己的 $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'])&& 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); } ?>
注意:如果你的设备中android操作系统是4.0以上的,那么要在主程序中加上下面一段代码,才能上传成功
strictmode.setthreadpolicy(new strictmode.threadpolicy.builder() .detectdiskreads() .detectdiskwrites() .detectnetwork() // or .detectall() for all detectable problems .penaltylog() .build()); strictmode.setvmpolicy(new strictmode.vmpolicy.builder() .detectleakedsqlliteobjects() .detectleakedclosableobjects() .penaltylog() .penaltydeath() .build());
如果是4.0以下的操作系统当然不用加了
下面是上传成功后的效果图:
读数据的方法讲放在下一篇《android通过json向mysql中读写数据的方法详解【读取篇】》中介绍
更多关于android相关内容感兴趣的读者可查看本站专题:《android操作json格式数据技巧总结》、《android数据库操作技巧总结》、《android编程之activity操作技巧总结》、《android文件操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android开发入门与进阶教程》、《android资源操作技巧汇总》、《android视图view技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。
上一篇: java IO流总结
下一篇: 深入浅析Java中的volatile