Android通過json向MySQL中讀寫資料的方法詳解【寫入篇】_Android

來源:互聯網
上載者:User

本文執行個體講述了Android通過json向MySQL中寫入資料的方法。分享給大家供大家參考,具體如下:

先說一下如何通過json將Android程式中的資料上傳到MySQL中:

首先定義一個類JSONParser.Java類,將json上傳資料的方法封裝好,可以直接在主程式中調用該類,代碼如下

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;}}

主程式中這樣調用:

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 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);}?>

注意:如果你的裝置中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程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.