
App Inventor 字典功能簡單應用
今天要來介紹,在 App Inventor 裡的字典功能,在使用上跟 List 差不多,也可以拿來讀取 Open Data 的資料,這次我會簡單的示範,如何讀取 YouBike 的站點名稱,那麼以下請跟著教學。
1. 開啟 App Inventor 並新增一個專案
元件只需要按鈕、標籤及網路元件就好

切換到程式設計
我們先來新增一個變數,右邊放 “建立一個字典“。
“鍵” 的部份我們分別放 “apple” 和 “banana“
“值” 的部份我們分別放 “蘋果” 和 “香蕉”

然後當按鈕被點選後,將標籤文字設為 “取得字典…中對應於鍵…” 方塊。
這樣顯示時就會是 “蘋果“

底下的其它功能除了”鍵路徑“我還搞不太懂之外,其餘的都很簡單,可以試著 print 看看。

最後來看怎麼讀取 YouBike 資料
2. 先把 d 變數改為 “建立空的字典“

當按鈕被點選要改成設定網址,並執行 GET 請求。
http://od-oas.kcg.gov.tw/api/service/Get/b4dd9c40-9027-4125-8666-06bef1756092

拖拉當網路元件取得文字方塊
裡面放設 d 變數為 “清單轉字典” 方塊,右邊放 JSON 解碼方塊。

因為回應內容是 json 格式,所以要先用解碼方塊,解碼後會變清單,所以再把清單轉成字典。
我們將資料拿去 Code Beautiful 分析,會發現我們要的站點名稱在 data 底下的,retVal 底下的 sna。
看到 retVal 的右邊有 [1006],[] -> 這個符號是清單的意思,所以等等在讀取底下的 sna 時,要用迴圈方塊,將裡面的 1006 筆站點名稱,顯示到我們的標籤。

回到剛剛的方塊,於底下直接加入清單迴圈方塊,右邊則放 “取得字典…中對應於鍵…” 方塊,依序為 data 和 retVal。

裡面再用一次 “取得字典…中對應於鍵…” 方塊,將站點名稱加到文字標籤。
如此即可成功查詢站點資料!!
App 完整程式方塊

App 專案程式檔案下載
App 範例執行畫面
如果覺得文章內容還不錯的話,麻煩請幫我點個讚!感謝
可以多點幾次喔~~
第一次點讚需使用 Google 或 Facebook 帳號註冊
