編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它是一種與程式語言無關的輕量級資料交換格式,因為語法簡潔、可讀性高,早已成為 XML 之外最主流的選擇。在 Android 開發中,幾乎所有需要與網路服務溝通的 App,都會收到伺服器回傳的 JSON 字串,因此學會解析 JSON,是必備的基本功。
Android SDK 內建四個與 JSON 相關的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。其中又以 JSONObject 與 JSONArray 最常使用。
動手之前,第一步永遠是「先看清楚你要的是什麼」。以下是一段典型的天氣 API 回應,我們真正感興趣的只有溫度:
{
"sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 },
"weather": [ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ],
"main": { "temp":304.15, "pressure":1009 }
}
在看程式碼之前,先認識 JSON 文件的四個構成要素:
第一步是把整段文字塞進 JSONObject 的建構子,讓它變成一個可供查詢的物件:
String in; JSONObject reader = new JSONObject(in);
第二步則是逐層往下取值。JSONObject 針對不同層級與型別提供了各自的方法,例如 getJSONObject() 取得下一層的物件,getString() 取得指定鍵的字串值:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
除了這兩個,JSONObject 還提供了更細緻的取值方法,可以依欄位型別挑選最合適的一個:
接下來我們把上面的觀念串起來,做一個可以輸入城市名稱、按下按鈕後向天氣 API 索取 JSON 並解析顯示的小應用。你可以在實機或模擬器上執行。
主活動程式 src/com.yiibai.jsonparser/MainActivity.java:
package com.example.jsonparser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void open(View view){
String url = location.getText().toString();
String finalUrl = url1 + url;
country.setText(finalUrl);
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());
}
}
負責抓取與解析的 src/com.yiibai.jsonparser/HandleJSON.java:
package com.example.jsonparser;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.annotation.SuppressLint;
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; }
@SuppressLint("NewApi") 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() : "";
}
}
版面配置 res/layout/activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView android:id="@+id/textView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginTop="15dp"
android:text="@string/location"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText android:id="@+id/editText1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true" android:ems="10" />
<TextView android:id="@+id/country" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/textView1"
android:layout_marginTop="68dp" android:text="@string/country" />
<EditText android:id="@+id/editText2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/country" android:ems="10" />
<TextView android:id="@+id/temperature" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/editText2"
android:layout_marginTop="19dp" android:text="@string/temperature" />
<EditText android:id="@+id/editText3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/temperature" android:ems="10" />
<TextView android:id="@+id/humidity" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/editText3"
android:layout_marginTop="21dp" android:text="@string/humidity" />
<EditText android:id="@+id/editText4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/humidity" android:ems="10" />
<TextView android:id="@+id/pressure" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/editText4"
android:layout_marginTop="21dp" android:text="@string/pressure" />
<EditText android:id="@+id/editText5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/pressure" android:ems="10" />
<Button android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/editText5"
android:onClick="open" android:text="@string/weather" />
</RelativeLayout>
字串資源 res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">JSONParser</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</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>
最後別忘了在 AndroidManifest.xml 加上 INTERNET 權限,否則程式會在連線時直接丟出例外:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.yiibai.jsonparser" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:allowBackup="true" android:icon="@drawable/ic_launcher"
android:label="@string/app_name" android:theme="@style/AppTheme" >
<activity android:name="com.yiibai.jsonparser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
編譯完成、把 App 裝到 AVD 或真機啟動,若一切設定正確,你會看到這樣的起始畫面:
在位置欄位輸入任一座城市,這裡以紐約為例,按下 Weather 按鈕:
按下按鈕後,App 會向天氣服務發出請求、取回 JSON 並解析,再把國家、溫度、濕度、氣壓分別填回四個欄位。
小提醒:這個 API 回傳的溫度單位是 Kelvin(克氏),304.15 K 看起來很嚇人,其實只是約 31 度。若要顯示一般人熟悉的攝氏度,記得做個轉換:攝氏 = 克氏 - 273.15。
Android 應用本地化:讓 App 說多國語言
同一支應用程式,可能會被安裝在台灣、義大利、德國或日本的裝置上。要讓不同地區的使用者都覺得順手,文字、數字、日期與檔案格式都得跟著系統語言環境調整,這就是「本地化」(Lo
Android 指針滑動動態效果實現思路
要實現指針滑動效果,可以先用 FrameLayout 將指針圖示疊在刻度或滾動條上方,再利用程式控制指針的位置變化,形成連續移動的視覺效果。動畫實現常見做法是開啟背景線程
動手做「開發者頭條」App(三):首頁整體實現
一、前言 本文是系列第三篇,來把開發者頭條的首頁搭起來。先看效果: 從動圖可以拆出兩層結構:外層是「精選、訂閱、發現」三個可左右滑動的 Tab;進入精選頁後,頂部是一塊
Android MediaPlayer:打造可播放、暫停與快轉的音樂播放器
Android 提供了多種控制音訊/影片播放的方式,其中最常用的是 MediaPlayer 類別。 MediaPlayer 讓我們存取系統內建的媒體播放服務來播放音訊、