序言
輕量級(jí)數(shù)據(jù)存儲(chǔ)功能通常用于保存應(yīng)用的一些常用配置信息,并不適合需要存儲(chǔ)大量數(shù)據(jù)和頻繁改變數(shù)據(jù)的場(chǎng)景。應(yīng)用的數(shù)據(jù)保存在文件中,這些文件可以持久化地存儲(chǔ)在設(shè)備上。需要注意的是,應(yīng)用訪問的實(shí)例包含文件所有數(shù)據(jù),這些數(shù)據(jù)會(huì)一直加載在設(shè)備的內(nèi)存中,直到應(yīng)用主動(dòng)從內(nèi)存中將其移除前,應(yīng)用可以通過Preferences的API進(jìn)行數(shù)據(jù)操作。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-683564.html
Preferences封裝
public class PreferencesUtil {
private static volatile PreferencesUtil instance;
private Context mContext;
private Preferences preferences;
private PreferencesUtil(Context context) {
mContext = context;
}
public static PreferencesUtil getInstance(Context context) {
if (instance == null) {
synchronized (PreferencesUtil.class) {
if (instance == null) {
instance = new PreferencesUtil(context);
}
}
}
return instance;
}
/**
* 獲取Preferences實(shí)例
*/
public PreferencesUtil getPreferences() {
if (preferences == null) {
DatabaseHelper databaseHelper = new DatabaseHelper(mContext); // context入?yún)㈩愋蜑閛hos.app.Context。
String fileName = "user_pref"; // fileName表示文件名,其取值不能為空,也不能包含路徑,默認(rèn)存儲(chǔ)目錄可以通過context.getPreferencesDir()獲取。
preferences = databaseHelper.getPreferences(fileName);
}
return this;
}
public String getUserName() {
if (preferences == null) {
throw new IllegalStateException("沒有獲取Preference實(shí)例,需要檢測(cè)代碼");
}
return preferences.getString("user_name", "");
}
public void setUserName(String userName) {
if (preferences == null) {
throw new IllegalStateException("沒有獲取Preference實(shí)例,需要檢測(cè)代碼");
}
preferences.putString("user_name", userName);
preferences.flush();
}
}
使用
PreferencesUtil.getInstance(getContext()).getPreferences().getUserName()
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-683564.html
到了這里,關(guān)于【Harmony】Preferences存儲(chǔ)的封裝使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!