sharedpreferences也是一種輕型的資料存儲方式,它的本質是基于xml檔案存儲key-value鍵值對資料,通常用來存儲一些簡單的配置資訊。其存儲位置在/data/data/<包名>/shared_prefs目錄下。
<code></code>
/*
* name 打開的sharedpreferences檔案名稱(不需要.xml字尾)
* mode 打開的sharedpreferences模式
*/
sharedpreferences getsharedpreferences (string name, int mode)
四種sharedpreferences擷取的模式
context.mode_private = 0
context.mode_world_readable = 1
context.mode_world_writeable = 2
context. mode_multi_process = 4
mode_private 為預設操作模式,代表該檔案是私有資料,隻能被應用本身通路,在該模式下寫入的内容會覆寫原檔案的内容。
mode_world_readable 表示目前檔案可以被其他應用讀取。
mode_world_writeable 表示目前檔案可以被其他應用寫入。
mode_multi_process sharedpreference的裝載标記,設定它,檔案将會在sharedpreference執行個體被裝載到程序的時候檢查是否被修改,主要用在一個應用有多個程序的情況。
使用sharedpreference的getxxx()擷取相應的資料,主要包括:
boolean getboolean(string key, boolean defvalue)
float getfloat(string key, float defvalue)
int getint(string key, int defvalue)
long getlong(string key, long defvalue)
string getstring(string key, string defvalue)
set<string> getstringset(string key, set<string> defvalues)
需要注意的是sharedpreferences對象本身隻能擷取資料而不支援存儲和修改,存儲修改是通過editor對象實作。
實作sharedpreferences存儲的步驟如下:
同讀取sharedpreferences擷取sharedpreferences對象步驟
通過sharedpreferences.edit()擷取editor對象
putboolean(string key, boolean value)
putfloat(string key, float value)
putint(string key, int value)
putlong(string key, long value)
putstring(string key, string value)
putstringset(string key, set<string> values)
tips:這裡有個問題,putxxx的傳回值是sharedpreferences.editor對象,android developer上面說的是:
returns a reference to the same editor object, so you can chain put calls together.
甚是不解,求大神解釋。
* return 如果成功送出新資料傳回true反之false
boolean commit()
tips:如果希望sharedpreferences背後使用的xml檔案能被其他應用讀和寫,可以指定context.mode_world_readable和context.mode_world_writeable權限。但是實際上即使用了mode_world_writeable權限,别的應用程式也是不能修改本程式的資料的。如果其他程式要修改本程式資料可以在配置檔案中使用android:shareduserid。