国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android通過json向MySQL中讀寫數(shù)據(jù)的方法詳解【寫入篇】

2019-12-12 06:07:06
字體:
供稿:網(wǎng)友

本文實(shí)例講述了Android通過json向MySQL中寫入數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

先說一下如何通過json將Android程序中的數(shù)據(jù)上傳到MySQL中:

首先定義一個(gè)類JSONParser.Java類,將json上傳數(shù)據(jù)的方法封裝好,可以直接在主程序中調(diào)用該類,代碼如下

public class JSONParser {static InputStream is = null;static JSONObject jObj = null;static String json = "";// constructorpublic JSONParser() {}// function get json from url// by making HTTP POSTpublic 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;}}

主程序中這樣調(diào)用:

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();//數(shù)據(jù)的php文件的路徑String url_up = "******/文件名字.php";try{JSONObject json = jsonParser.makeHttpRequest(url_up,"POST", params);Log.v("uploadsucceed", "uploadsucceed");}catch(Exception e){e.printStackTrace();}

最后就是定義一個(gè)接收數(shù)據(jù)的php文件:

<?php// array for JSON response//此處需要將數(shù)據(jù)庫名和表明還有密碼做相應(yīng)修改,改成你自己的$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 fieldsif (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 notif ($result) {// successfully inserted into database$response["success"] = 1;$response["message"] = "Product successfully created.";// echoing JSON responseecho json_encode($response);} else {// failed to insert row$response["success"] = 0;$response["message"] = "Oops! An error occurred.";// echoing JSON responseecho json_encode($response);}} else {// required field is missing$response["success"] = 0;$response["message"] = "Required field(s) is missing";// echoing JSON responseecho json_encode($response);}?>

注意:如果你的設(shè)備中android操作系統(tǒng)是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以下的操作系統(tǒng)當(dāng)然不用加了

下面是上傳成功后的效果圖:

讀數(shù)據(jù)的方法講放在下一篇《Android通過json向MySQL中讀寫數(shù)據(jù)的方法詳解【讀取篇】》中介紹

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫操作技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)

希望本文所述對大家Android程序設(shè)計(jì)有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 天气| 友谊县| 英吉沙县| 桃源县| 漾濞| 八宿县| 南宁市| 会昌县| 平塘县| 新津县| 剑河县| 靖远县| 晋州市| 上饶市| 邻水| 漳州市| 和龙市| 响水县| 鹤岗市| 墨脱县| 彝良县| 连南| 双峰县| 汉川市| 稻城县| 伊宁县| 灵璧县| 旬邑县| 嘉定区| 海门市| 防城港市| 交口县| 商城县| 绿春县| 临沭县| 石景山区| 冀州市| 禹城市| 綦江县| 邢台县| 阿坝县|