Presentation is loading. Please wait.

Presentation is loading. Please wait.

讀取網路資料及JSON開放資料 靜宜大學資管系 楊子青

Similar presentations


Presentation on theme: "讀取網路資料及JSON開放資料 靜宜大學資管系 楊子青"— Presentation transcript:

1 讀取網路資料及JSON開放資料 靜宜大學資管系 楊子青

2 1. 讀取網路資料 Android Http連線 以往作法 建議作法:統一改用HttpURLConnection
Get method: 使用HttpGet與HttpClient class Post method: 使用URLEncoder與URLConnection Apache HTTP Client Removal from API23 如果要使用,需自行安裝jar 建議作法:統一改用HttpURLConnection

3 AsyncTask非同步任務 專門用來處理背景任務與UI的類別
Android 4.0 之後,所有的網路行為,都不能在主執行緒(Main Thread,又稱UI執行緒)執行 任何UI元件都在主執行緒中執行,若是程式佔據主執行緒很久(如按了一個按鈕後,整個App停住五秒),使用者體驗會非常差 因此許多耗時的程式建議在背景執行,最常見的是網路的功能

4 測試文件檔 tcyang_about1.txt: 楊子青 靜宜大學資管系 Tel: 04-26328001-18110
研究室:靜宜大學 主顧樓579R 個人網頁: 用記事本編輯,存成urf8格式,傳到網路空間 例如:

5 專案:ReadJsonExample 介面設計 修改成LinearLayout (vertical) TextView
新增一個button在txv上方 Text為 讀取網路資料 textSize為 20sp onClick為 ReadWebData

6 加入網路存取權限 manifests\AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

7 MainActivity.java程式碼 import android.app.ProgressDialog;
import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;

8 MainActivity.java程式碼 public void ReadWebData(View v){
public class MainActivity extends AppCompatActivity { 裡面加入: public void ReadWebData(View v){ new AsyncRetrieve().execute(); }

9 MainActivity.java程式碼 public class MainActivity extends AppCompatActivity { 裡面加入: public class AsyncRetrieve extends AsyncTask<String, String, String> { ProgressDialog pdLoading = new ProgressDialog(MainActivity.this); HttpURLConnection conn; URL url = null; //this method will interact with UI, here display loading message @Override protected void onPreExecute() { super.onPreExecute(); pdLoading.setMessage("\t讀取資料中,請稍候..."); pdLoading.setCancelable(false); pdLoading.show(); }

10 MainActivity.java程式碼 // This method does not interact with UI, You need to pass result to onPostExecute to display @Override protected String doInBackground(String... params) { try { // 初始化 URL url = new URL(" // 取得連線物件 conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); // setDoOutput to true as we recieve data from json file conn.setDoOutput(true); // 讀取資料 BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8")); String result = "", line; while ((line = reader.readLine()) != null) { result += line; } // Pass data to onPostExecute method return(result); } catch (IOException e) { e.printStackTrace(); return e.toString(); } finally { conn.disconnect();

11 MainActivity.java程式碼 // this method will interact with UI, display result sent from doInBackground method @Override protected void onPostExecute(String result) { pdLoading.dismiss(); TextView txv = (TextView) findViewById(R.id.txv); txv.setText(result); }

12 執行結果

13 2. JSON JavaScript Object Notation
is a format for storing and transporting data is lightweight data interchange format (非常輕量級的資料交換格式) JSON is language independent * The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language JSON is "self-describing" and easy to understand.

14 JSON格式 物件(object)用大括號 { } 陣列(array)用中括號 [ ]

15 JSON Example { "employees":[ ] }
{"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }

16 Example obj.employees[1].firstName + " " + obj.employees[1].lastName;
<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p id="demo"></p> <script> var text = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script> </body> </html>

17 測試文件檔 tcyang_about2.txt: 用記事本編輯,存成urf8格式,傳到網路空間
[ {"學校":"靜宜大學", "地址":"台中市沙鹿區台灣大道七段200號"}, {"學校":"東海大學", "地址":"台中市西屯區台灣大道四段1727號"}, {"學校":"逢甲大學", "地址":"台中市西屯區文華路100號"} ] 用記事本編輯,存成urf8格式,傳到網路空間 例如:

18 MainActivity.java程式碼修改
AsyncRetrieve裡的doInBackground,修改原先的網址: // 初始化 URL //url = new URL(" url = new URL("

19 JSONObject與JSONArray

20 JSON Parse (解析) protected void onPostExecute(String result) {
pdLoading.dismiss(); TextView txv = (TextView) findViewById(R.id.txv); //txv.setText(result); try { String jsonResult = ""; JSONArray array = new JSONArray(result); for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); jsonResult += row.getString("學校") + "," + row.getString("地址") + "\n"; } txv.setText(jsonResult); } catch (JSONException e) { e.printStackTrace();

21 3. Open Data實例 政府資料開放平台 http://data.gov.tw/,輸入JSON關鍵字
左邊的「資料集提供機關」,選擇「行政院農業委員會 」,有一個「國家森林遊樂區」 說明頁: JSON資料:

22 原始JSON檔案內容

23 使用Online JSON Viewer觀看
Text頁籤,選Load JSON data按鈕,輸入JSON檔案的網址

24 分析結果 切換到Viewer頁籤

25 修改MainActivity.java程式碼
protected String doInBackground(String... params) { try { // 初始化 URL //url = new URL(" //url = new URL(" url = new URL(" protected void onPostExecute(String result) { try { String jsonResult = ""; JSONArray array = new JSONArray(result); for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); //jsonResult += row.getString("學校") + "," + row.getString("地址") + "\n"; jsonResult += String.valueOf(i) + row.getString("遊樂區名稱") + "," + row.getString("特色景觀") + "\n";

26 讀取開放資料之執行結果

27 加入ScrollView讓文字可上下捲動
刪除ScrollView伴隨的Linearlayout 將txv拖入ScrollView


Download ppt "讀取網路資料及JSON開放資料 靜宜大學資管系 楊子青"

Similar presentations


Ads by Google