首页

源码搜藏网

首页 > 开发教程 > 手机开发 >

Android中通过json向MySql中读写数据的方法

创建时间:2016-05-12 11:51  

先说一下如何通过json将Android程序中的数据上传到MySQL中:

首先定义一个类JSONParser.Java类,将json上传数据的方法封装好,可以直接在主程序中调用该类,代码如下

 

[java] view plain copy
 
  1. public class JSONParser {   
  2. static InputStream is = null;   
  3. static JSONObject jObj = null;   
  4. static String json = "";   
  5. // constructor   
  6. public JSONParser() {   
  7. }   
  8. // function get json from url   
  9. // by making HTTP POST   
  10. public JSONObject makeHttpRequest(String url, String method,   
  11. List<NameValuePair> params) {   
  12. // Making HTTP request   
  13. try {   
  14. // request method is POST   
  15. // defaultHttpClient   
  16. DefaultHttpClient httpClient = new DefaultHttpClient();   
  17. HttpPost httpPost = new HttpPost(url);   
  18. httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));   
  19. HttpResponse httpResponse = httpClient.execute(httpPost);   
  20. HttpEntity httpEntity = httpResponse.getEntity();   
  21. is = httpEntity.getContent();   
  22. catch (UnsupportedEncodingException e) {   
  23. e.printStackTrace();   
  24. catch (ClientProtocolException e) {   
  25. e.printStackTrace();   
  26. catch (IOException e) {   
  27. e.printStackTrace();   
  28. }   
  29. try {   
  30. BufferedReader reader = new BufferedReader(new InputStreamReader(   
  31. is, "UTF-8"));   
  32. StringBuilder sb = new StringBuilder();   
  33. String line = null;   
  34. while ((line = reader.readLine()) != null) {   
  35. sb.append(line + "\n");   
  36. }   
  37. is.close();   
  38. json = sb.toString();   
  39. catch (Exception e) {   
  40. Log.e("Buffer Error""Error converting result " + e.toString());   
  41. Log.d("json", json.toString());   
  42. }   
  43. // try parse the string to a JSON object   
  44. try {   
  45. jObj = new JSONObject(json);   
  46. catch (JSONException e) {   
  47. Log.e("JSON Parser""Error parsing data " + e.toString());   
  48. }   
  49. // return JSON String   
  50. return jObj;   
  51. }   
  52. }   


 

[java] view plain copy
 
  1.   

主程序中这样调用:

         

[java] view plain copy
 
  1.                                params = new ArrayList<NameValuePair>();   
  2.      //这里可以替换成你自己程序中的一些键值对  
  3. params.add(new BasicNameValuePair("time"""+time));   
  4. params.add(new BasicNameValuePair("lat"""+lat));   
  5. params.add(new BasicNameValuePair("lon"""+lon));  
  6. params.add(new BasicNameValuePair("encyptiontype",encyptiontype));   
  7. params.add(new BasicNameValuePair("rssi",rssi));   
  8. params.add(new BasicNameValuePair("name",name));   
  9.   
  10.   
  11. JSONParser jsonParser = new JSONParser();  
  12. 数据的php文件的路径  
  13. String url_up = "******/文件名字.php";  
  14.   
  15. try{   
  16. JSONObject json = jsonParser.makeHttpRequest(url_up,"POST", params);   
  17. Log.v("uploadsucceed""uploadsucceed");   
  18.   
  19. }catch(Exception e){   
  20. e.printStackTrace();   
  21. }   

 

 

最后就是定义一个接收数据的php文件:

 

[php] view plain copy
 
  1. <php   
  2. // array for JSON response   
  3.   
  4. //此处需要将数据库名和表明还有密码做相应修改,改成你自己的  
  5. $con = mysql_connect("localhost","root",null);  
  6. if (!$con) {  
  7. die('Could not connect:'.mysql_error() );  
  8. }  
  9. mysql_select_db("a0722152915"$con);  
  10.   
  11.   
  12.   
  13.   
  14. $response = array();   
  15. include("conn.php");   
  16. // check for required fields   
  17. if (isset($_POST['time']) && isset($_POST['lat']) && isset($_POST['lon'])&& isset($_POST['encyptiontype'])&& isset($_POST['rssi'])&& isset($_POST['name'])) {   
  18. $time = $_POST['time'];   
  19. $lat = $_POST['lat'];   
  20. $lon = $_POST['lon'];   
  21. $encyptiontype = $_POST['encyptiontype'];   
  22. $rssi = $_POST['rssi'];   
  23. $name = $_POST['name'];   
  24. $result = mysql_query("INSERT INTO wifi_state(time, lat, lon,encyptiontype,rssi,name) VALUES('$time', '$lat', '$lon','$encyptiontype','$rssi','$name')");   
  25. echo $result;   
  26. // check if row inserted or not   
  27. if ($result) {   
  28. // successfully inserted into database   
  29. $response["success"] = 1;   
  30. $response["message"] = "Product successfully created.";   
  31. // echoing JSON response   
  32. echo json_encode($response);   
  33. else {   
  34. // failed to insert row   
  35. $response["success"] = 0;   
  36. $response["message"] = "Oops! An error occurred.";   
  37. // echoing JSON response   
  38. echo json_encode($response);   
  39. }   
  40. else {   
  41. // required field is missing   
  42. $response["success"] = 0;   
  43. $response["message"] = "Required field(s) is missing";   
  44. // echoing JSON response   
  45. echo json_encode($response);   
  46. }   
  47. >   


 

注意:如果你的设备中android操作系统是4.0以上的,那么要在主程序中加上下面一段代码,才能上传成功

 

 

[java] view plain copy
 
  1. StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()    
  2.         .detectDiskReads()    
  3.         .detectDiskWrites()    
  4.         .detectNetwork()   // or .detectAll() for all detectable problems    
  5.         .penaltyLog()    
  6.         .build());    
  7.         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()    
  8.         .detectLeakedSqlLiteObjects()    
  9.         .detectLeakedClosableObjects()    
  10.         .penaltyLog()    
  11.         .penaltyDeath()    
  12.         .build());   


 

如果是4.0以下的操作系统当然不用加了

下面是上传成功后的效果图:

Android中通过json向MySql中读写数据的方法

读数据的方法放在下一篇介绍 

上一篇:Android中通过json向MySql中读写数据的方法(二)
下一篇:如何在Android应用程序中创建和查看日志报表

相关内容

热门推荐