顯示廣告
隱藏 ✕
看板 KnucklesNote
作者 Knuckles (站長 那克斯)
標題 [AndroidStudio] 使用 SharedPreferences 儲存資料
時間 2016-02-15 Mon. 04:32:22


要將簡單的 key-value 資料儲存在手機上
可以使用 SharedPreferences

使用方法

取得 APP 的 SharedPreferences
    SharedPreferences sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
其中 "myPrefs" 是存在手機上的檔名
使用 MODE_PRIVATE 代表不允許其他 APP 存取這個資料

要讀取其中一筆資料時,例如要取得儲存的"name"值,使用
    String name = sharedPreferences.getString("name", "");
第二個參數""代表"name"不存在時,傳出空字串

要寫入資料時,要使用 Editor,例如要寫入 "name"="knuckles"
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("name", "knuckles");
    editor.commit();


參考
http://developer.android.com/intl/zh-tw/guide/topics/data/data-storage.html#pref
http://www.tutorialspoint.com/android/android_shared_preferences.htm


關於 SharedPreferences 的效能與技巧

參考:http://blog.yakivmospan.com/best-practices-for-sharedpreferences/

除了使用 editor.commit(); 將資料同步寫入 SharePreferences
也可以用 editor.apply(); 將資料用非同步的方法寫入
apply() 會快一點,但 commit() 比較安全

Editor 的其他指令
// remove single value by key
editor.remove("key");

// remove all values
editor.clear();

// commit your putted values to the SharedPreferences object synchronously
// returns true if success
boolean result = editor.commit();

// do the same as commit() but asynchronously (faster but not safely)
// returns nothing
editor.apply(); 


SharedPreferences 是一個 Singletone 物件
可以在不同的類別裡分別建立,只有第一次建立時會開啟儲存的檔案
// There are 1000 String values in preferences

SharedPreferences first = getSharedPreferences("myPrefs", Context.MODE_PRIVATE); 
// call time = 4 milliseconds

SharedPreferences second = getSharedPreferences("myPrefs", Context.MODE_PRIVATE); 
// call time = 0 milliseconds

SharedPreferences third = getSharedPreferences("myPrefs", Context.MODE_PRIVATE); 
// call time = 0 milliseconds

因為是 Singletone 物件,所以不用擔心資料內容會不相同
first.edit().putInt("key",15).commit();

int firstValue = first.getInt("key",0)); // firstValue is 15  
int secondValue = second.getInt("key",0)); // secondValue is also 15

要儲存的值很多的時候建議拆分成不同的檔案來儲存

APP更新版本後,儲存的資料不會被清掉
所以要注意更新版本後舊資料的格式會不會影響到新的程式

SharedPreferences 是以 xml 的檔案格式存在 APP 的 data 資料夾
// yours preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/myPrefs.xml

// default preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml




--
※ 作者: Knuckles 時間: 2016-02-15 04:32:22
※ 編輯: Knuckles 時間: 2016-02-17 05:52:24
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 489 
分享網址: 複製 已複製
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇