Android通過json向MySQL中讀寫數(shù)據(jù)的方法詳解【寫入篇】
本文實例講述了Android通過json向MySQL中寫入數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
先說一下如何通過json將Android程序中的數(shù)據(jù)上傳到MySQL中:
首先定義一個類JSONParser.Java類,將json上傳數(shù)據(jù)的方法封裝好,可以直接在主程序中調(diào)用該類,代碼如下
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; } }
主程序中這樣調(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(); }
最后就是定義一個接收數(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 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); } ?>
注意:如果你的設(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è)計有所幫助。
相關(guān)文章
android 仿微信demo——微信通訊錄界面功能實現(xiàn)(移動端,服務(wù)端)
本系列文章主要介紹了微信小程序-閱讀小程序?qū)嵗╠emo),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望能給你們提供幫助2021-06-06Android intent之間復(fù)雜參數(shù)傳遞方法詳解
這篇文章主要介紹了Android intent之間復(fù)雜參數(shù)傳遞方法,較為詳細(xì)的分析了Android中intent參數(shù)傳遞的常見方法與使用技巧,需要的朋友可以參考下2016-10-10Android實現(xiàn)簡易計算器(可以實現(xiàn)連續(xù)計算)
這篇文章主要為大家詳細(xì)介紹了Android實現(xiàn)簡易計算器,可以實現(xiàn)連續(xù)計算,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-03-03ViewPager和SlidingPaneLayout的滑動事件沖突解決方法
下面小編就為大家分享一篇ViewPager和SlidingPaneLayout的滑動事件沖突解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01系統(tǒng)應(yīng)用根據(jù)Uri授予權(quán)限方法詳解
這篇文章主要為大家介紹了系統(tǒng)應(yīng)用根據(jù)Uri授予權(quán)限方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Android ScrollView實現(xiàn)向上滑動控件頂部懸浮效果
這篇文章主要為大家詳細(xì)介紹了Android ScrollView實現(xiàn)向上滑動控件頂部懸浮效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05詳解Android如何設(shè)計一個全局可調(diào)用的ViewModel對象
很多時候我們需要維護(hù)一個全局可用的ViewModel,因為這樣可以維護(hù)全局同一份數(shù)據(jù)源,且方便使用協(xié)程綁定App的生命周期,那如何設(shè)計全局可用的ViewModel對象,文中介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05A07_TimePicker & DatePicker & AnalogClock & Digi
本文將帶領(lǐng)大家一起學(xué)習(xí)時間日期和時鐘的設(shè)置。A07_TimePicker & DatePicker & AnalogClock & DigitalClock 的設(shè)置,感興趣的朋友可以參考下哈2013-06-06