TShopping

 找回密碼
 註冊
搜索
查看: 2346|回復: 0

[教學] Android如何用JSON非同步獲取網頁MYSQL資料

[複製鏈接]
發表於 2016-2-26 17:59:27 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
在ANDROID要抓取SERVER上的MYSQL資料庫欄位資料時
需要會ANDROID及PHP語法


以下是完成圖
androidgetmysql.png

首先PHP SERVER下設置一檔案index_phone.php

  1. <?php
  2. include "config.php";
  3. //提取資料庫範例資料

  4. $sql="SELECT * FROM net_company ORDER BY num ASC";
  5. $query=mysql_query($sql);
  6. while($e=mysql_fetch_assoc($query))
  7. $output[]=$e;
  8. print(json_encode($output));
  9. mysql_close();
  10. ?>
複製代碼

config.php就是mysql相關設定檔
  1. <?php
  2. $mydbhost                ="localhost";                //配置主機
  3. $mydbuser                ="xxx";                        //數據庫用戶
  4. $mydbpw                        ="xxx";                                //數據庫密碼
  5. $mydbname                ="xxx";                //數據庫密碼
  6. $mydbcharset        ="UTF8";

  7. $db = @mysql_connect($mydbhost,$mydbuser,$mydbpw);
  8. if (!$db) {
  9.         exit('Unable connect MYSQL at this time.');
  10. }
  11. if (!@mysql_select_db($mydbname)) {
  12.         exit ('Unable connect DB at this time.');
  13. }
  14. //宣告資料庫要寫入的格式
  15. mysql_query("SET NAMES $mydbcharset", $db);
  16. //================

  17. ?>
複製代碼


在activity_main.xml設置圖面
兩個TEXTVIEW及一個TableLayout
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     android:layout_width="fill_parent"
  3.     android:layout_height="fill_parent"
  4.     android:orientation="vertical" >

  5.     <TextView
  6.         android:id="@+id/textView1"
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:text="TextView" />

  10.     <TextView
  11.         android:id="@+id/textView2"
  12.         android:layout_width="wrap_content"
  13.         android:layout_height="wrap_content"
  14.         android:text="TextView" />
  15.     <TableLayout
  16.         android:id="@+id/user_list"
  17.         android:layout_width="match_parent"
  18.         android:layout_height="wrap_content" />

  19. </LinearLayout>
複製代碼


在manifest.xml加入網路權限,很重要,不然會無法連線
  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
複製代碼

最後主程式MainActivity.java網頁讀取MYSQL資料採用非同步讀取
AsyncTask,切記一定要用非同步的doInBackground(String... urls)
讀網址,不然會出現錯誤,詳細狀況還未釐清清楚
  1. package com.example.appgetsql;

  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;

  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import org.json.JSONArray;
  11. import org.json.JSONException;
  12. import org.json.JSONObject;

  13. import android.app.ActionBar.LayoutParams;
  14. import android.app.Activity;
  15. import android.net.ConnectivityManager;
  16. import android.net.NetworkInfo;
  17. import android.os.AsyncTask;
  18. import android.os.Bundle;
  19. import android.util.Log;
  20. import android.view.Gravity;
  21. import android.widget.TableLayout;
  22. import android.widget.TableRow;
  23. import android.widget.TextView;
  24. import android.widget.Toast;



  25. public class MainActivity extends Activity {
  26.         TextView tv1,tv2;
  27.         TableLayout user_list;
  28.         String data1 = null,data2;
  29.         @Override
  30.         protected void onCreate(Bundle savedInstanceState) {
  31.                 super.onCreate(savedInstanceState);
  32.                 setContentView(R.layout.activity_main);
  33.                 tv1 = (TextView)findViewById(R.id.textView1);
  34.                 tv2 = (TextView)findViewById(R.id.textView2);
  35.                 user_list = (TableLayout)findViewById(R.id.user_list);
  36.                 user_list.setStretchAllColumns(true);
  37.         
  38.                
  39.                 String uri = "http://xxx/index_phone.php";  
  40.             String TAG_STRING = "file path";
  41.             // check if you are connected or not
  42.         if(isConnected()){
  43.             tv1.setBackgroundColor(0xFF00CC00);
  44.             tv1.setText("You are conncted");
  45.         }
  46.         else{
  47.             tv1.setText("You are NOT conncted");
  48.         }

  49.         // call AsynTask to perform network operation on separate thread
  50.         new HttpAsyncTask().execute("http://demo.netyea.com/index_phone.php");
  51.                  
  52.         }
  53.         public boolean isConnected(){
  54.         ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
  55.             NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  56.             if (networkInfo != null && networkInfo.isConnected())
  57.                 return true;
  58.             else
  59.                 return false;   
  60.     }
  61.         private static String convertInputStreamToString(InputStream inputStream) throws IOException, JSONException{
  62.         BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
  63.         String line = "";
  64.         String result = "";
  65.         while((line = bufferedReader.readLine()) != null)
  66.             result += line;
  67.         inputStream.close();
  68.         
  69.         return result;

  70.     }
  71.         public static String GET(String url){
  72.         InputStream inputStream = null;
  73.         String result = "";
  74.         try {
  75.             // create HttpClient
  76.             HttpClient httpclient = new DefaultHttpClient();
  77.             // make GET request to the given URL
  78.             HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
  79.             // receive response as inputStream
  80.             inputStream = httpResponse.getEntity().getContent();
  81.             // convert inputstream to string
  82.             if(inputStream != null)
  83.                 result = convertInputStreamToString(inputStream);
  84.             else
  85.                 result = "Did not work!";

  86.         } catch (Exception e) {
  87.             Log.d("InputStream", e.getLocalizedMessage());
  88.         }

  89.         return result;
  90.     }
  91.         private class HttpAsyncTask extends AsyncTask<String, Void, String> {
  92.         protected String doInBackground(String... urls) {

  93.             return GET(urls[0]);
  94.         }
  95.         // onPostExecute displays the results of the AsyncTask.
  96.         @Override
  97.         protected void onPostExecute(String result) {
  98.             Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
  99.             TableLayout.LayoutParams row_layout = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  100.             TableRow.LayoutParams view_layout = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  101.                         try {
  102.                                 JSONArray jArray = new JSONArray(result);
  103.                                 for (int i=0;i<jArray.length();i++) {
  104.                                         JSONObject json_data = jArray.getJSONObject(i);
  105.                                     /*data1 = json_data.getString("id");
  106.                                     data2 = json_data.getString("subject");
  107.                                     tv1.setText(data1+":"+data2 );*/
  108.                                     
  109.                                     TableRow tr = new TableRow(MainActivity.this);
  110.                     tr.setLayoutParams(row_layout);
  111.                     tr.setGravity(Gravity.CENTER_HORIZONTAL);
  112.                     
  113.                     TextView user_id = new TextView(MainActivity.this);
  114.                     user_id.setText(json_data.getString("id"));
  115.                     user_id.setLayoutParams(view_layout);
  116.                     
  117.                     TextView user_subject = new TextView(MainActivity.this);
  118.                     user_subject.setText(json_data.getString("subject"));
  119.                     user_subject.setLayoutParams(view_layout);
  120.                                        
  121.                     tr.addView(user_id);
  122.                     tr.addView(user_subject);
  123.                     
  124.                     user_list.addView(tr);
  125.                                 }
  126.                         } catch (JSONException e) {
  127.                                 // TODO 自動產生的 catch 區塊
  128.                                 e.printStackTrace();
  129.                         } // convert String to JSONObject
  130.        }
  131.     }
  132.         
  133. }
複製代碼

完成,以上是參考網路文章再自行修改測試成功程式碼

參考資料

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-28 16:58 , Processed in 0.045989 second(s), 24 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表