編輯:Android 開發實例
幾乎所有真實的 App 都要跟網路打交道,而「按下按鈕 → 發請求 → 拿 JSON → 解析 → 更新畫面」就是最典型的一條鏈路。本章用一個天氣查詢 App 把這條鏈路完整走一遍,並在過程中說明每個環節容易出錯的地方。
JSON(JavaScript Object Notation)之所以能取代 XML 成為主流,關鍵在於它精簡:沒有結束標籤、沒有屬性宣告,同一份資料的傳輸量與解析成本都低得多。Android 內建 JSONObject、JSONArray、JSONStringer、JSONTokenizer 四個類別來處理它。
我們要從回應中取出國家代碼與溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 元素 | 說明 |
|---|---|
| Array [] | 方括號是陣列,weather 屬於這一種。 |
| Object {} | 大括號是物件,sys 與 main 都是。 |
| Key | 物件中的鍵,一定是字串。 |
| Value | 值可以是字串、整數、浮點數或布林。 |
把字串交給 JSONObject,再逐層取值:
String in; JSONObject reader = new JSONObject(in);
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
getJSONObject() 往下鑽一層,getString() 取出指定鍵的字串值。若需要其他型別,還有 getInt()、getDouble()、getBoolean()、getLong()、length() 與 names() 等方法可用。
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立 JSONParser 專案,Target SDK 選新版。 |
| 2 | 修改 MainActivity.java,加入 open() 事件。 |
| 3 | 修改 activity_main.xml 加入五組標籤與輸入框、一顆查詢鈕。 |
| 4 | 修改 res/values/string.xml 加入字串。 |
| 5 | 新增 HandleJSON.java 處理連線與解析。 |
| 6 | 在 AndroidManifest.xml 加上 INTERNET 權限。 |
| 7 | 執行並驗證結果。 |
MainActivity.java:
package com.example.jsonparser; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { private String url1 = "https://api.openweathermap.org/data/2.5/weather?q="; private EditText location,country,temperature,humidity,pressure; private HandleJSON obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); location = (EditText)findViewById(R.id.editText1); country = (EditText)findViewById(R.id.editText2); temperature = (EditText)findViewById(R.id.editText3); humidity = (EditText)findViewById(R.id.editText4); pressure = (EditText)findViewById(R.id.editText5); } public void open(View view){ String finalUrl = url1 + location.getText().toString(); obj = new HandleJSON(finalUrl); obj.fetchJSON(); while(obj.parsingComplete); country.setText(obj.getCountry()); temperature.setText(obj.getTemperature()); humidity.setText(obj.getHumidity()); pressure.setText(obj.getPressure()); } }
HandleJSON.java 中,fetchJSON() 開一條新執行緒做連線,readAndParseJSON() 專心解析:
package com.example.jsonparser; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class HandleJSON { private String country = "county"; private String temperature = "temperature"; private String humidity = "humidity"; private String pressure = "pressure"; private String urlString = null; public volatile boolean parsingComplete = true; public HandleJSON(String url){ this.urlString = url; } public String getCountry(){ return country; } public String getTemperature(){ return temperature; } public String getHumidity(){ return humidity; } public String getPressure(){ return pressure; } public void readAndParseJSON(String in) { try { JSONObject reader = new JSONObject(in); JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp"); pressure = main.getString("pressure"); humidity = main.getString("humidity"); parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchJSON(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); InputStream stream = conn.getInputStream(); String data = convertStreamToString(stream); readAndParseJSON(data); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("A"); return s.hasNext() ? s.next() : ""; } }
activity_main.xml(省略純樣式屬性):
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textV1" android:text="@string/location" /> <EditText android:id="@+id/editText1" android:layout_toRightOf="@id/textV1" /> <TextView android:id="@+id/textV2" android:text="@string/country" android:layout_below="@id/editText1" /> <EditText android:id="@+id/editText2" android:layout_below="@id/editText1" /> <TextView android:id="@+id/textV3" android:text="@string/temperature" android:layout_below="@id/editText2" /> <EditText android:id="@+id/editText3" android:layout_below="@id/editText2" /> <TextView android:id="@+id/textV4" android:text="@string/humidity" android:layout_below="@id/editText3" /> <EditText android:id="@+id/editText4" android:layout_below="@id/editText3" /> <TextView android:id="@+id/textV5" android:text="@string/pressure" android:layout_below="@id/editText4" /> <EditText android:id="@+id/editText5" android:layout_below="@id/editText4" /> <Button android:id="@+id/button1" android:onClick="open" android:text="@string/weather" /> </RelativeLayout>
string.xml 與 AndroidManifest.xml(務必加 INTERNET 權限):
<resources> <string name="app_name">JSONParser</string> <string name="location">Location</string> <string name="country">Country:</string> <string name="temperature">Temperature:</string> <string name="humidity">Humidity:</string> <string name="pressure">Pressure:</string> <string name="weather">Weather</string> </resources> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
啟動 App 後畫面如下,五個欄位分別對應位置與四項氣象資料:
輸入城市名稱(範例為紐約)後按下查詢按鈕:
App 會連上服務、取回 JSON 並解析填表。最後三個提醒:回傳的溫度是開爾文,攝氏度請減 273.15;範例中的 while 迴圈只是為了教學等待,正式專案應改用非同步回呼或 LiveData 之類的機制,避免空轉消耗 CPU;此外 Android 不允許在主執行緒做網路連線,這也是為什麼範例一定要開新執行緒。
Android MediaPlayer 範例:音樂播放與快進快退
本範例展示一個簡單的音樂播放器,包含播放、暫停、快進與倒退功能。適合初學者理解 MediaPlayer 的基本生命週期。 播放控制 播放時可取得總長度與目前位置,並更新
Android自定義Dialog實戰詳解:帶WebView與多按鈕的彈窗
工作一個多月了,對 Android 的很多東西都有了新的認識,或者說才真正掌握。為了讓更多像我當初那樣的新手少走彎路,我會堅持把工作中遇到的、印象深刻的知識點整理出來分享
Android 圖片縮放與旋轉:Matrix 的靜態與動態兩種玩法
Matrix 是 Android 做圖形變形的基礎工具,縮放與旋轉都只是它的其中兩個方法。本文用兩個層次不同的範例來說明:先做一次性變形,再做可依輸入即時調整的動態版本。
Android 開發實作:TabHost 分頁元件完整解析
做過其他語言開發的人,對標籤頁(Tab)元件應該都不陌生。在 Android 上,當一個畫面塞不下所有元件時,常見的解法有兩種:一是用滾動視圖把內容往下疊,二是用標籤把畫