第九堂 手機的資料保存
TRANSCRIPT
第九堂:手機的資料保存
柯力中 Jason Ko
Jason 的 Android 快樂應用程式學習班
課程內容• 使用 SharePreference
• Android 的資料庫: SQLite
• ContentProvider 內容提供器
• 完成 NoteBook App
Jason 的 Android 快樂應用程式學習班
Jason 的 Android 快樂應用程式學習班
At Beginning
https://github.com/KosbrotherSchool/Teach_NoteBook_Before
使用 SharePreference
Jason 的 Android 快樂應用程式學習班
SharePreference• SharePreference 是在手機 data 資料夾下
的 xml 檔 , 以 key, value 的方式儲存 , 適合用來存簡單資料
Jason 的 Android 快樂應用程式學習班
ex. 使用 SharePreference 記錄初始狀態
Jason 的 Android 快樂應用程式學習班
• 如果是第一次進入 APP, 彈出 dialog => “ 感謝您使用 NoteBook, 請先點擊右上角新增文章”
SQLite 資料庫
Jason 的 Android 快樂應用程式學習班
SQLite 資料庫• 當我們需要儲存大量資料時 , 就必須使用資料
庫
• SQLite 不需要設定 , 也不需要資料庫伺服器
• SQLite 是一個單檔資料庫 , 依賴檔案系統的安全機制
Jason 的 Android 快樂應用程式學習班
DbHelper• DbHelper 是一個可以和 SQLite 互動的介面
元件
• DbHelper 提供資料增 , 刪 , 改 , 查的動作 , 分別是 insert(), delete(), update(), query()
Jason 的 Android 快樂應用程式學習班
為何不直接使用 SQLite
• 避免資料庫攻擊 SQLite injection attack
• 提高效能 , 避免一直執行 SQLite 指令
Jason 的 Android 快樂應用程式學習班
DB 檔案結構示意圖
Jason 的 Android 快樂應用程式學習班
DbContract記錄 db 會用到的常數
DbHelper存取 db Activity取 db
ex. 當文章儲存時 , 寫入到 db
1. 寫一個 DbContract 來儲存 db 會用到的各種常數
2. 撰寫 DbHelper extends SQLiteOpenHelper
3. 當按儲存時 , 寫入文章到 SQLite 資料庫
Jason 的 Android 快樂應用程式學習班
DbContract
Jason 的 Android 快樂應用程式學習班
• 使用 db 會用到的各種常數
DbHelper
Jason 的 Android 快樂應用程式學習班
• 繼承自 SQLiteHelper, 用來 create Table, 取得 db 等
DB 設定檔案連結
Jason 的 Android 快樂應用程式學習班
https://drive.google.com/file/d/0B-Z1UBSQ9xtTeW1fS2ZYNEdBMEE/view
db 的增刪改查
Jason 的 Android 快樂應用程式學習班
增 insert :
刪 delete :
改 update :
查 update :
Selection 和 SelectionArgs
Jason 的 Android 快樂應用程式學習班
SelectionSelectionArgs
• selection 是 where 的描述 , SelectionArgs 給值
adb 與 SQLite
Jason 的 Android 快樂應用程式學習班
1. 在 Terminal 或 命令式字元下指令 adb shell 可以 adb 進入 device
2. cd /data/data/com.xxxxx 進入 APP 的資料夾
3. 找到 database_name.db4. sqlite3 database_name.db 進入
database5. .schema 可以看到 Table6. .dump 可以看到目前有的 data7. ctrl + z 離開 sqlite38. exit 離開 adb shel
ContentProvider 內容提供器
Jason 的 Android 快樂應用程式學習班
ContentProvider 內容提供器• ContentProvider 可以想成是程式資料的介面
• 將資料庫跟 App 程式間做更好的分離
• ContentProvider 可以提供其他 App 資料ex. 通訊錄 , 系統設定 ... 等 , 就是利用此方式來提供資料
Jason 的 Android 快樂應用程式學習班
URI 識別• URI 是一個識別特定資源的字串
• Android 透過 URI 來識別 ContentProvider
Jason 的 Android 快樂應用程式學習班
DB 檔案結構示意圖
Jason 的 Android 快樂應用程式學習班
DbContract記錄
db 會用到的
常數
ContentProvid
er存取 db Activity
取 dbDbHelper
ex. 製作 ContentProvider1. 建立 ContentProvider.java
2. 宣告 CONTENT_RUI
3. 實作 insert(), update(), delete(), query() 等 db 方法
4. 在 AndroidManifest.xml 中宣告此 ContentProvider
Jason 的 Android 快樂應用程式學習班
完成 NoteBook App
Jason 的 Android 快樂應用程式學習班
ex. 完成 Notebook App
1. 儲存的 action button 按下的時候 , insert() 或 update()
2. 刪除的 action button 按下的時候 , delete()
3. 傳 id 進來時 , query() 並顯示
Jason 的 Android 快樂應用程式學習班
ContentActivity.java
MainActivity.java
1. query() 並顯示現有資料在 ListView 上
2. 當 ListView 被點擊時 , 轉到 ContentActivity 並附帶 note_id
Jason 的 Android 快樂應用程式學習班
Final
https://github.com/KosbrotherSchool/Teach_NoteBook_After