HarmonyOS基礎(chǔ)技術(shù)賦能之輕量級數(shù)據(jù)庫Preferencens
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
引言
輕量級數(shù)據(jù)存儲(chǔ)適用于對Key-Value結(jié)構(gòu)的數(shù)據(jù)進(jìn)行存取和持久化操作。主要用于保存應(yīng)用的一些常用配置,并不適合存儲(chǔ)大量數(shù)據(jù)和頻繁改變數(shù)據(jù)的場景。用戶的數(shù)據(jù)保存在文件中,可以持久化的存儲(chǔ)在設(shè)備上。需要注意的是用戶訪問的實(shí)例包含文件所有數(shù)據(jù),并一直加載在設(shè)備的內(nèi)存中,并通過輕量級數(shù)據(jù)存儲(chǔ)的API完成數(shù)據(jù)操作。
功能介紹
輕量級數(shù)據(jù)存儲(chǔ)向本地應(yīng)用提供的API支持本地應(yīng)用讀寫數(shù)據(jù)及觀察數(shù)據(jù)變化。數(shù)據(jù)存儲(chǔ)形式為鍵值對,鍵的類型為字符串型(String),值的存儲(chǔ)數(shù)據(jù)類型包括整型(int)、字符串型(String)、布爾型(boolean)、浮點(diǎn)型(float)、長整型(long)、字符串型Set集合(Set
開發(fā)指南
1. 創(chuàng)建Preferences實(shí)例。
- // context為上下文對象,PREFERENCE_FILE_NAME為輕量級數(shù)據(jù)庫文件名,String類型,可以自定義
- databaseHelper = new DatabaseHelper(context);
- preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME);
2. 將數(shù)據(jù)寫入指定文件。
- // preferences.putString()為存入String類型的數(shù)據(jù)
- preferences.putString(String key, String value);
- // flush()為異步持久化數(shù)據(jù);flushSync()為同步持久化數(shù)據(jù)
- preferences.flush()/preferences.flushSync();
3.從指定文件讀取數(shù)據(jù)。
- //讀取時(shí)傳入的key, 要與寫入時(shí)傳入的key一致,才能獲取對應(yīng)數(shù)據(jù),第二個(gè)參數(shù)為默認(rèn)值。
- preferences.getString(String key, String default)
4. 開發(fā)者可以向Preferences實(shí)例注冊觀察者,觀察數(shù)據(jù)更新變化。
- private class PreferencesObserverImpl implements Preferences.PreferencesObserver {
- @Override
- public void onChange(Preferences preferences, String key) {
- if ("key".equals(key)) {
- HiLog.info(LABLE, "Change Received:[key=value]");
- }
- }
- }
- // 向preferences實(shí)例注冊觀察者
- PreferencesObserverImpl observer = new PreferencesObserverImpl();
- preferences.registerObserver(observer);
- // 修改數(shù)據(jù)后,observer的onChange方法會(huì)被回調(diào)
- // 向preferences實(shí)例注銷觀察者
- preferences.unRegisterObserver(observer);
源碼如下:
1.PreferenceUtils
- public class PreferenceUtils {
- private static String PREFERENCE_FILE_NAME = "prefrence_file";
- private static Preferences preferences;
- private static DatabaseHelper databaseHelper;
- private static PreferencesObserver mPreferencesObserver;
- private static void initPreference(Context context){
- if(databaseHelper==null){
- databaseHelper = new DatabaseHelper(context);
- }
- if(preferences==null){
- preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME);
- }
- }
- //存放、獲取時(shí)傳入的context必須是同一個(gè)context,否則存入的數(shù)據(jù)無法獲取
- public static void putString(Context context, String key, String value) {
- initPreference(context);
- preferences.putString(key, value);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取的String 默認(rèn)值為:null
- */
- public static String getString(Context context, String key) {
- initPreference(context);
- return preferences.getString(key, null);
- }
- public static void putInt(Context context, String key, int value) {
- initPreference(context);
- preferences.putInt(key, value);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取int的默認(rèn)值為:-1
- */
- public static int getInt(Context context, String key) {
- initPreference(context);
- return preferences.getInt(key, -1);
- }
- public static void putLong(Context context, String key, long value) {
- initPreference(context);
- preferences.putLong(key, value);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取long的默認(rèn)值為:-1
- */
- public static long getLong(Context context, String key) {
- initPreference(context);
- return preferences.getLong(key, -1L);
- }
- public static void putBoolean(Context context, String key, boolean value) {
- initPreference(context);
- preferences.putBoolean(key, value);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取boolean的默認(rèn)值為:false
- */
- public static boolean getBoolean(Context context, String key) {
- initPreference(context);
- return preferences.getBoolean(key, false);
- }
- public static void putFloat(Context context, String key, float value) {
- initPreference(context);
- preferences.putFloat(key, value);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取float的默認(rèn)值為:0.0
- */
- public static float getFloat(Context context, String key) {
- initPreference(context);
- return preferences.getFloat(key, 0.0F);
- }
- public static void putStringSet(Context context, String key, Set<String> set) {
- initPreference(context);
- preferences.putStringSet(key, set);
- preferences.flush();
- }
- /**
- * @param context 上下文
- * @param key 鍵
- * @return 獲取set集合的默認(rèn)值為:null
- */
- public static Set<String> getStringSet(Context context, String key) {
- initPreference(context);
- return preferences.getStringSet(key, null);
- }
- public static boolean deletePreferences(Context context) {
- initPreference(context);
- boolean isDelete= databaseHelper.deletePreferences(PREFERENCE_FILE_NAME);
- return isDelete;
- }
- public static void registerObserver(Context context,PreferencesObserver preferencesObserver){
- initPreference(context);
- mPreferencesObserver=preferencesObserver;
- preferences.registerObserver(mPreferencesObserver);
- }
- public static void unregisterObserver(){
- if(mPreferencesObserver!=null){
- // 向preferences實(shí)例注銷觀察者
- preferences.unregisterObserver(mPreferencesObserver);
- }
- }
- }
2. MainAbilitySlice
- public class MainAbilitySlice extends AbilitySlice implements ClickedListener {
- private TextField tfName;
- private TextField tfGener;
- private TextField tfAge;
- private TextField tfWeight;
- private Text tvResultQuery;
- private Text tvResultListener;
- private String name;
- private boolean isMan;
- private int age;
- private float weight;
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setUIContent(ResourceTable.Layout_ability_main);
- tfName=(TextField)findComponentById(ResourceTable.Id_tf_name);
- tfGener=(TextField)findComponentById(ResourceTable.Id_tf_isMan);
- tfAge=(TextField)findComponentById(ResourceTable.Id_tf_age);
- tfWeight=(TextField)findComponentById(ResourceTable.Id_tf_weight);
- tvResultQuery=(Text) findComponentById(ResourceTable.Id_tvResultQuery);
- tvResultListener=(Text) findComponentById(ResourceTable.Id_tvResultListener);
- Button btSave=(Button)findComponentById(ResourceTable.Id_bt_save);
- Button btQuery=(Button)findComponentById(ResourceTable.Id_bt_query);
- Button btRegister=(Button)findComponentById(ResourceTable.Id_bt_regist);
- Button btUnRegister=(Button)findComponentById(ResourceTable.Id_bt_unregist);
- btSave.setClickedListener(this);
- btQuery.setClickedListener(this);
- btRegister.setClickedListener(this);
- btUnRegister.setClickedListener(this);
- }
- @Override
- public void onActive() {
- super.onActive();
- }
- @Override
- public void onForeground(Intent intent) {
- super.onForeground(intent);
- }
- @Override
- public void onClick(Component component) {
- switch (component.getId()){
- case ResourceTable.Id_bt_save:
- PreferenceUtils.putString(MyApplication.mContext,"name",tfName.getText());
- if(tfGener.getText().equals("男")){
- PreferenceUtils.putBoolean(MyApplication.mContext,"gender",true);
- }
- try {
- String age=tfAge.getText();
- String weight=tfWeight.getText();
- int ageInt=Integer.parseInt(age);
- float weightFloat=Float.parseFloat(weight);
- PreferenceUtils.putInt(MyApplication.mContext,"age",ageInt);
- PreferenceUtils.putFloat(MyApplication.mContext,"weight",weightFloat);
- }catch (Exception e){
- e.printStackTrace();
- }
- new ToastDialog(this).setDuration(2000).setText("保存成功").setAlignment(LayoutAlignment.CENTER).show();
- break;
- case ResourceTable.Id_bt_query:
- name=PreferenceUtils.getString(MyApplication.mContext,"name");
- isMan=PreferenceUtils.getBoolean(MyApplication.mContext,"gender");
- age=PreferenceUtils.getInt(MyApplication.mContext,"age");
- weight=PreferenceUtils.getFloat(MyApplication.mContext,"weight");
- if(isMan){
- tvResultQuery.setText("查詢結(jié)果:"+name+"/男/"+age+"/"+weight);
- }else {
- tvResultQuery.setText("查詢結(jié)果:"+name+"/女/"+age+"/"+weight);
- }
- new ToastDialog(this).setDuration(2000).setText("查詢成功").setAlignment(LayoutAlignment.CENTER).show();
- break;
- case ResourceTable.Id_bt_regist:
- PreferenceUtils.registerObserver(this,new PreferencesObserver() {
- @Override
- public void onChange(Preferences preferences, String key) {
- switch (key){
- case "name":
- name=PreferenceUtils.getString(MyApplication.mContext,"name");
- break;
- case "gender":
- isMan=PreferenceUtils.getBoolean(MyApplication.mContext,"gender");
- break;
- case "age":
- age=PreferenceUtils.getInt(MyApplication.mContext,"age");
- break;
- case "weight":
- weight=PreferenceUtils.getFloat(MyApplication.mContext,"weight");
- break;
- }
- if(isMan){
- tvResultListener.setText("兼停結(jié)果:"+name+"/男/"+age+"/"+weight);
- }else {
- tvResultListener.setText("兼停結(jié)果:"+name+"/女/"+age+"/"+weight);
- }
- }
- });
- new ToastDialog(this).setDuration(2000).setText("注冊成功").setAlignment(LayoutAlignment.CENTER).show();
- break;
- case ResourceTable.Id_bt_unregist:
- PreferenceUtils.unregisterObserver();
- new ToastDialog(this).setDuration(2000).setText("解除注冊成功").setAlignment(LayoutAlignment.CENTER).show();
- break;
- }
- }
- }
3. MyApplication
- public class MyApplication extends AbilityPackage {
- public static Context mContext ;
- @Override
- public void onInitialize() {
- super.onInitialize();
- mContext=this;
- }
- }
4.頁面布局ability_main.xml文件
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_parent"
- ohos:orientation="vertical"
- ohos:width="match_parent">
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="vertical"
- ohos:left_padding="15vp"
- ohos:right_padding="15vp"
- ohos:top_padding="16vp">
- <Text
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="姓名"
- ohos:text_size="18vp"/>
- <TextField
- ohos:id="$+id:tf_name"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:text_input_type="pattern_text"
- ohos:hint="請輸入姓名"
- ohos:text_size="18vp"
- ohos:hint_color="#cccccc"
- ohos:top_margin="8vp"/>
- <DirectionalLayout
- ohos:height="1vp"
- ohos:width="match_parent"
- ohos:top_margin="3vp"
- ohos:background_element="#cccccc"/>
- </DirectionalLayout>
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="vertical"
- ohos:left_padding="15vp"
- ohos:right_padding="15vp"
- ohos:top_padding="16vp">
- <Text
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="性別"
- ohos:text_size="18vp"/>
- <TextField
- ohos:id="$+id:tf_isMan"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:text_input_type="pattern_text"
- ohos:hint="男/女"
- ohos:text_size="18vp"
- ohos:hint_color="#cccccc"
- ohos:top_margin="8vp"/>
- <DirectionalLayout
- ohos:height="1vp"
- ohos:width="match_parent"
- ohos:top_margin="3vp"
- ohos:background_element="#cccccc"/>
- </DirectionalLayout>
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="vertical"
- ohos:left_padding="15vp"
- ohos:right_padding="15vp"
- ohos:top_padding="16vp">
- <Text
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="年齡"
- ohos:text_size="18vp"/>
- <TextField
- ohos:id="$+id:tf_age"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:text_input_type="pattern_number"
- ohos:hint="請輸入年齡"
- ohos:text_size="18vp"
- ohos:hint_color="#cccccc"
- ohos:top_margin="8vp"/>
- <DirectionalLayout
- ohos:height="1vp"
- ohos:width="match_parent"
- ohos:top_margin="3vp"
- ohos:background_element="#cccccc"/>
- </DirectionalLayout>
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="vertical"
- ohos:left_padding="15vp"
- ohos:right_padding="15vp"
- ohos:top_padding="16vp">
- <Text
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="體重"
- ohos:text_size="18vp"/>
- <TextField
- ohos:id="$+id:tf_weight"
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:text_input_type="pattern_number"
- ohos:hint="請輸入體重"
- ohos:text_size="18vp"
- ohos:hint_color="#cccccc"
- ohos:top_margin="8vp"/>
- <DirectionalLayout
- ohos:height="1vp"
- ohos:width="match_parent"
- ohos:top_margin="3vp"
- ohos:background_element="#cccccc"/>
- </DirectionalLayout>
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="horizontal"
- ohos:top_margin="30vp"
- ohos:left_margin="15vp"
- ohos:right_margin="15vp">
- <Button
- ohos:id="$+id:bt_save"
- ohos:height="40vp"
- ohos:width="0"
- ohos:weight="1"
- ohos:text="保存"
- ohos:text_size="20vp"
- ohos:text_color="#ffffff"
- ohos:right_margin="30vp"
- ohos:background_element="$graphic:background_main_circle"
- ohos:layout_alignment="center"/>
- <Button
- ohos:id="$+id:bt_query"
- ohos:height="40vp"
- ohos:width="0"
- ohos:weight="1"
- ohos:text="查詢"
- ohos:text_size="20vp"
- ohos:text_color="#ffffff"
- ohos:right_margin="30vp"
- ohos:background_element="$graphic:background_main_circle"
- ohos:layout_alignment="center"/>
- </DirectionalLayout>
- <DirectionalLayout
- ohos:height="match_content"
- ohos:width="match_parent"
- ohos:orientation="horizontal"
- ohos:top_margin="30vp"
- ohos:left_margin="15vp"
- ohos:right_margin="15vp">
- <Button
- ohos:id="$+id:bt_regist"
- ohos:height="40vp"
- ohos:width="0"
- ohos:weight="1"
- ohos:text="注冊兼停"
- ohos:text_size="20vp"
- ohos:text_color="#ffffff"
- ohos:right_margin="30vp"
- ohos:background_element="$graphic:background_main_circle"
- ohos:layout_alignment="center"/>
- <Button
- ohos:id="$+id:bt_unregist"
- ohos:height="40vp"
- ohos:width="0"
- ohos:weight="1"
- ohos:text="解除注冊"
- ohos:text_size="20vp"
- ohos:text_color="#ffffff"
- ohos:right_margin="30vp"
- ohos:background_element="$graphic:background_main_circle"
- ohos:layout_alignment="center"/>
- </DirectionalLayout>
- <Text
- ohos:id="$+id:tvResultQuery"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text_size="18vp"
- ohos:text="查詢結(jié)果:"
- ohos:background_element="#cccccc"
- ohos:layout_alignment="center"
- ohos:top_margin="30vp"
- ohos:padding="10vp"/>
- <Text
- ohos:id="$+id:tvResultListener"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text_size="18vp"
- ohos:text="兼停結(jié)果:"
- ohos:background_element="#cccccc"
- ohos:layout_alignment="center"
- ohos:top_margin="30vp"
- ohos:padding="10vp"/>
- </DirectionalLayout>
5.圓角背景圖形background_main_circle.xml文件
- <?xml version="1.0" encoding="UTF-8" ?>
- <shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:shape="rectangle">
- <corners
- ohos:radius="10"/>
- <solid
- ohos:color="#00aaf5"/>
- </shape>
實(shí)現(xiàn)效果視頻:https://harmonyos.51cto.com/show/7929
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)