HarmonyOS基础技术赋能之轻量级数据库Preferencens

数据库 其他数据库 OpenHarmony
轻量级数据存储适用于对Key-Value结构的数据进行存取和持久化操作。主要用于保存应用的一些常用配置,并不适合存储大量数据和频繁改变数据的场景。

[[420676]]

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

引言

轻量级数据存储适用于对Key-Value结构的数据进行存取和持久化操作。主要用于保存应用的一些常用配置,并不适合存储大量数据和频繁改变数据的场景。用户的数据保存在文件中,可以持久化的存储在设备上。需要注意的是用户访问的实例包含文件所有数据,并一直加载在设备的内存中,并通过轻量级数据存储的API完成数据操作。

功能介绍

轻量级数据存储向本地应用提供的API支持本地应用读写数据及观察数据变化。数据存储形式为键值对,键的类型为字符串型(String),值的存储数据类型包括整型(int)、字符串型(String)、布尔型(boolean)、浮点型(float)、长整型(long)、字符串型Set集合(Set)。

开发指南

1. 创建Preferences实例。

  1. // context为上下文对象,PREFERENCE_FILE_NAME为轻量级数据库文件名,String类型,可以自定义 
  2. databaseHelper = new DatabaseHelper(context); 
  3. preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME); 

2. 将数据写入指定文件。

  1. // preferences.putString()为存入String类型的数据 
  2. preferences.putString(String key, String value); 
  3. // flush()为异步持久化数据;flushSync()为同步持久化数据 
  4. preferences.flush()/preferences.flushSync(); 

3.从指定文件读取数据。

  1. //读取时传入的key, 要与写入时传入的key一致,才能获取对应数据,第二个参数为默认值。 
  2.   preferences.getString(String key, String default

4. 开发者可以向Preferences实例注册观察者,观察数据更新变化。

  1. private class PreferencesObserverImpl implements Preferences.PreferencesObserver { 
  2.     
  3.     @Override     
  4.     public void onChange(Preferences preferences, String key) { 
  5.         if ("key".equals(key)) { 
  6.            HiLog.info(LABLE, "Change Received:[key=value]");         
  7.         }     
  8.     } 
  9.  
  10.  
  11. // 向preferences实例注册观察者 
  12. PreferencesObserverImpl observer = new PreferencesObserverImpl(); 
  13. preferences.registerObserver(observer); 
  14. // 修改数据后,observer的onChange方法会被回调 
  15. // 向preferences实例注销观察者 
  16. preferences.unRegisterObserver(observer); 

源码如下:

1.PreferenceUtils

  1. public class PreferenceUtils { 
  2.  
  3.   private static String PREFERENCE_FILE_NAME = "prefrence_file"
  4.   private static Preferences preferences; 
  5.   private static DatabaseHelper databaseHelper; 
  6.   private static PreferencesObserver mPreferencesObserver; 
  7.  
  8.   private static void initPreference(Context context){ 
  9.     if(databaseHelper==null){ 
  10.       databaseHelper = new DatabaseHelper(context); 
  11.     } 
  12.     if(preferences==null){ 
  13.       preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME); 
  14.     } 
  15.  
  16.   } 
  17.  
  18.   //存放、获取时传入的context必须是同一个context,否则存入的数据无法获取 
  19.   public static void putString(Context context, String key, String value) { 
  20.     initPreference(context); 
  21.     preferences.putString(key, value); 
  22.     preferences.flush(); 
  23.   } 
  24.  
  25.   /** 
  26.    * @param context 上下文 
  27.    * @param key  键 
  28.    * @return 获取的String 默认值为:null 
  29.    */ 
  30.   public static String getString(Context context, String key) { 
  31.     initPreference(context); 
  32.     return preferences.getString(keynull); 
  33.   } 
  34.  
  35.  
  36.   public static void putInt(Context context, String keyint value) { 
  37.     initPreference(context); 
  38.     preferences.putInt(key, value); 
  39.     preferences.flush(); 
  40.   } 
  41.  
  42.   /** 
  43.    * @param context 上下文 
  44.    * @param key 键 
  45.    * @return 获取int的默认值为:-1 
  46.    */ 
  47.   public static int getInt(Context context, String key) { 
  48.     initPreference(context); 
  49.     return preferences.getInt(key, -1); 
  50.   } 
  51.  
  52.  
  53.   public static void putLong(Context context, String key, long value) { 
  54.     initPreference(context); 
  55.     preferences.putLong(key, value); 
  56.     preferences.flush(); 
  57.   } 
  58.  
  59.   /** 
  60.    * @param context 上下文 
  61.    * @param key  键 
  62.    * @return 获取long的默认值为:-1 
  63.    */ 
  64.   public static long getLong(Context context, String key) { 
  65.     initPreference(context); 
  66.     return preferences.getLong(key, -1L); 
  67.   } 
  68.  
  69.  
  70.   public static void putBoolean(Context context, String key, boolean value) { 
  71.     initPreference(context); 
  72.     preferences.putBoolean(key, value); 
  73.     preferences.flush(); 
  74.   } 
  75.  
  76.   /** 
  77.    * @param context  上下文 
  78.    * @param key  键 
  79.    * @return 获取boolean的默认值为:false 
  80.    */ 
  81.   public static boolean getBoolean(Context context, String key) { 
  82.     initPreference(context); 
  83.     return preferences.getBoolean(keyfalse); 
  84.   } 
  85.  
  86.  
  87.   public static void putFloat(Context context, String keyfloat value) { 
  88.     initPreference(context); 
  89.     preferences.putFloat(key, value); 
  90.     preferences.flush(); 
  91.   } 
  92.  
  93.   /** 
  94.    * @param context 上下文 
  95.    * @param key   键 
  96.    * @return 获取float的默认值为:0.0 
  97.    */ 
  98.   public static float getFloat(Context context, String key) { 
  99.     initPreference(context); 
  100.     return preferences.getFloat(key, 0.0F); 
  101.   } 
  102.  
  103.  
  104.   public static void putStringSet(Context context, String keySet<String> set) { 
  105.     initPreference(context); 
  106.     preferences.putStringSet(keyset); 
  107.     preferences.flush(); 
  108.   } 
  109.  
  110.   /** 
  111.    * @param context  上下文 
  112.    * @param key 键 
  113.    * @return 获取set集合的默认值为:null 
  114.    */ 
  115.   public static Set<String> getStringSet(Context context, String key) { 
  116.     initPreference(context); 
  117.     return preferences.getStringSet(keynull); 
  118.   } 
  119.  
  120.  
  121.   public static boolean deletePreferences(Context context) { 
  122.     initPreference(context); 
  123.     boolean isDelete= databaseHelper.deletePreferences(PREFERENCE_FILE_NAME); 
  124.     return isDelete; 
  125.   } 
  126.  
  127.  
  128.   public static void registerObserver(Context context,PreferencesObserver preferencesObserver){ 
  129.     initPreference(context); 
  130.     mPreferencesObserver=preferencesObserver; 
  131.     preferences.registerObserver(mPreferencesObserver); 
  132.   } 
  133.  
  134.   public static void unregisterObserver(){ 
  135.     if(mPreferencesObserver!=null){ 
  136.       // 向preferences实例注销观察者 
  137.       preferences.unregisterObserver(mPreferencesObserver); 
  138.     } 
  139.   } 
  140.  

2. MainAbilitySlice

  1. public class MainAbilitySlice extends AbilitySlice implements ClickedListener { 
  2.   private TextField tfName; 
  3.   private TextField tfGener; 
  4.   private TextField tfAge; 
  5.   private TextField tfWeight; 
  6.   private Text tvResultQuery; 
  7.   private Text tvResultListener; 
  8.   private String name
  9.   private boolean isMan; 
  10.   private int age; 
  11.   private float weight; 
  12.  
  13.  
  14.   @Override 
  15.   public void onStart(Intent intent) { 
  16.     super.onStart(intent); 
  17.     super.setUIContent(ResourceTable.Layout_ability_main); 
  18.     tfName=(TextField)findComponentById(ResourceTable.Id_tf_name); 
  19.     tfGener=(TextField)findComponentById(ResourceTable.Id_tf_isMan); 
  20.     tfAge=(TextField)findComponentById(ResourceTable.Id_tf_age); 
  21.     tfWeight=(TextField)findComponentById(ResourceTable.Id_tf_weight); 
  22.     tvResultQuery=(Text) findComponentById(ResourceTable.Id_tvResultQuery); 
  23.     tvResultListener=(Text) findComponentById(ResourceTable.Id_tvResultListener); 
  24.     Button btSave=(Button)findComponentById(ResourceTable.Id_bt_save); 
  25.     Button btQuery=(Button)findComponentById(ResourceTable.Id_bt_query); 
  26.     Button btRegister=(Button)findComponentById(ResourceTable.Id_bt_regist); 
  27.     Button btUnRegister=(Button)findComponentById(ResourceTable.Id_bt_unregist); 
  28.     btSave.setClickedListener(this); 
  29.     btQuery.setClickedListener(this); 
  30.     btRegister.setClickedListener(this); 
  31.     btUnRegister.setClickedListener(this); 
  32.   } 
  33.  
  34.   @Override 
  35.   public void onActive() { 
  36.     super.onActive(); 
  37.   } 
  38.  
  39.   @Override 
  40.   public void onForeground(Intent intent) { 
  41.     super.onForeground(intent); 
  42.   } 
  43.  
  44.   @Override 
  45.   public void onClick(Component component) { 
  46.     switch (component.getId()){ 
  47.       case ResourceTable.Id_bt_save: 
  48.         PreferenceUtils.putString(MyApplication.mContext,"name",tfName.getText()); 
  49.         if(tfGener.getText().equals("男")){ 
  50.           PreferenceUtils.putBoolean(MyApplication.mContext,"gender",true); 
  51.         } 
  52.         try { 
  53.           String age=tfAge.getText(); 
  54.           String weight=tfWeight.getText(); 
  55.           int ageInt=Integer.parseInt(age); 
  56.           float weightFloat=Float.parseFloat(weight); 
  57.           PreferenceUtils.putInt(MyApplication.mContext,"age",ageInt); 
  58.           PreferenceUtils.putFloat(MyApplication.mContext,"weight",weightFloat); 
  59.         }catch (Exception e){ 
  60.           e.printStackTrace(); 
  61.         } 
  62.         new ToastDialog(this).setDuration(2000).setText("保存成功").setAlignment(LayoutAlignment.CENTER).show(); 
  63.         break; 
  64.       case ResourceTable.Id_bt_query: 
  65.          name=PreferenceUtils.getString(MyApplication.mContext,"name"); 
  66.          isMan=PreferenceUtils.getBoolean(MyApplication.mContext,"gender"); 
  67.          age=PreferenceUtils.getInt(MyApplication.mContext,"age"); 
  68.          weight=PreferenceUtils.getFloat(MyApplication.mContext,"weight"); 
  69.         if(isMan){ 
  70.           tvResultQuery.setText("查询结果:"+name+"/男/"+age+"/"+weight); 
  71.         }else { 
  72.           tvResultQuery.setText("查询结果:"+name+"/女/"+age+"/"+weight); 
  73.         } 
  74.         new ToastDialog(this).setDuration(2000).setText("查询成功").setAlignment(LayoutAlignment.CENTER).show(); 
  75.         break; 
  76.       case ResourceTable.Id_bt_regist: 
  77.         PreferenceUtils.registerObserver(this,new PreferencesObserver() { 
  78.           @Override 
  79.           public void onChange(Preferences preferences, String key) { 
  80.             switch (key){ 
  81.               case "name"
  82.                  name=PreferenceUtils.getString(MyApplication.mContext,"name"); 
  83.                 break; 
  84.               case "gender"
  85.                  isMan=PreferenceUtils.getBoolean(MyApplication.mContext,"gender"); 
  86.                 break; 
  87.               case "age"
  88.                  age=PreferenceUtils.getInt(MyApplication.mContext,"age"); 
  89.                 break; 
  90.               case "weight"
  91.                  weight=PreferenceUtils.getFloat(MyApplication.mContext,"weight"); 
  92.                 break; 
  93.             } 
  94.             if(isMan){ 
  95.               tvResultListener.setText("兼停结果:"+name+"/男/"+age+"/"+weight); 
  96.             }else { 
  97.               tvResultListener.setText("兼停结果:"+name+"/女/"+age+"/"+weight); 
  98.             } 
  99.           } 
  100.  
  101.         }); 
  102.         new ToastDialog(this).setDuration(2000).setText("注册成功").setAlignment(LayoutAlignment.CENTER).show(); 
  103.         break; 
  104.       case ResourceTable.Id_bt_unregist: 
  105.         PreferenceUtils.unregisterObserver(); 
  106.         new ToastDialog(this).setDuration(2000).setText("解除注册成功").setAlignment(LayoutAlignment.CENTER).show(); 
  107.         break; 
  108.     } 
  109.  
  110.   } 
  111.  
  112.  
  113.  

3. MyApplication

  1. public class MyApplication extends AbilityPackage { 
  2.   public static Context mContext ; 
  3.  
  4.   @Override 
  5.   public void onInitialize() { 
  6.     super.onInitialize(); 
  7.     mContext=this; 
  8.   } 

4.页面布局ability_main.xml文件

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.   xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.   ohos:height="match_parent" 
  5.   ohos:orientation="vertical" 
  6.   ohos:width="match_parent"
  7.  
  8.   <DirectionalLayout 
  9.     ohos:height="match_content" 
  10.     ohos:width="match_parent" 
  11.     ohos:orientation="vertical" 
  12.     ohos:left_padding="15vp" 
  13.     ohos:right_padding="15vp" 
  14.     ohos:top_padding="16vp"
  15.     <Text 
  16.       ohos:height="match_content" 
  17.       ohos:width="match_content" 
  18.       ohos:text="姓名" 
  19.       ohos:text_size="18vp"/> 
  20.     <TextField 
  21.       ohos:id="$+id:tf_name" 
  22.       ohos:height="match_content" 
  23.       ohos:width="match_parent" 
  24.       ohos:text_input_type="pattern_text" 
  25.       ohos:hint="请输入姓名" 
  26.       ohos:text_size="18vp" 
  27.       ohos:hint_color="#cccccc" 
  28.       ohos:top_margin="8vp"/> 
  29.     <DirectionalLayout 
  30.       ohos:height="1vp" 
  31.       ohos:width="match_parent" 
  32.       ohos:top_margin="3vp" 
  33.       ohos:background_element="#cccccc"/> 
  34.   </DirectionalLayout> 
  35.  
  36.  
  37.   <DirectionalLayout 
  38.     ohos:height="match_content" 
  39.     ohos:width="match_parent" 
  40.     ohos:orientation="vertical" 
  41.     ohos:left_padding="15vp" 
  42.     ohos:right_padding="15vp" 
  43.     ohos:top_padding="16vp"
  44.     <Text 
  45.       ohos:height="match_content" 
  46.       ohos:width="match_content" 
  47.       ohos:text="性别" 
  48.       ohos:text_size="18vp"/> 
  49.     <TextField 
  50.       ohos:id="$+id:tf_isMan" 
  51.       ohos:height="match_content" 
  52.       ohos:width="match_parent" 
  53.       ohos:text_input_type="pattern_text" 
  54.       ohos:hint="男/女" 
  55.       ohos:text_size="18vp" 
  56.       ohos:hint_color="#cccccc" 
  57.       ohos:top_margin="8vp"/> 
  58.     <DirectionalLayout 
  59.       ohos:height="1vp" 
  60.       ohos:width="match_parent" 
  61.       ohos:top_margin="3vp" 
  62.       ohos:background_element="#cccccc"/> 
  63.   </DirectionalLayout> 
  64.  
  65.  
  66.   <DirectionalLayout 
  67.     ohos:height="match_content" 
  68.     ohos:width="match_parent" 
  69.     ohos:orientation="vertical" 
  70.     ohos:left_padding="15vp" 
  71.     ohos:right_padding="15vp" 
  72.     ohos:top_padding="16vp"
  73.     <Text 
  74.       ohos:height="match_content" 
  75.       ohos:width="match_content" 
  76.       ohos:text="年龄" 
  77.       ohos:text_size="18vp"/> 
  78.     <TextField 
  79.       ohos:id="$+id:tf_age" 
  80.       ohos:height="match_content" 
  81.       ohos:width="match_parent" 
  82.       ohos:text_input_type="pattern_number" 
  83.       ohos:hint="请输入年龄" 
  84.       ohos:text_size="18vp" 
  85.       ohos:hint_color="#cccccc" 
  86.       ohos:top_margin="8vp"/> 
  87.     <DirectionalLayout 
  88.       ohos:height="1vp" 
  89.       ohos:width="match_parent" 
  90.       ohos:top_margin="3vp" 
  91.       ohos:background_element="#cccccc"/> 
  92.   </DirectionalLayout> 
  93.  
  94.  
  95.   <DirectionalLayout 
  96.     ohos:height="match_content" 
  97.     ohos:width="match_parent" 
  98.     ohos:orientation="vertical" 
  99.     ohos:left_padding="15vp" 
  100.     ohos:right_padding="15vp" 
  101.     ohos:top_padding="16vp"
  102.     <Text 
  103.       ohos:height="match_content" 
  104.       ohos:width="match_content" 
  105.       ohos:text="体重" 
  106.       ohos:text_size="18vp"/> 
  107.     <TextField 
  108.       ohos:id="$+id:tf_weight" 
  109.       ohos:height="match_content" 
  110.       ohos:width="match_parent" 
  111.       ohos:text_input_type="pattern_number" 
  112.       ohos:hint="请输入体重" 
  113.       ohos:text_size="18vp" 
  114.       ohos:hint_color="#cccccc" 
  115.       ohos:top_margin="8vp"/> 
  116.     <DirectionalLayout 
  117.       ohos:height="1vp" 
  118.       ohos:width="match_parent" 
  119.       ohos:top_margin="3vp" 
  120.       ohos:background_element="#cccccc"/> 
  121.   </DirectionalLayout> 
  122.  
  123.  
  124.  
  125.   <DirectionalLayout 
  126.     ohos:height="match_content" 
  127.     ohos:width="match_parent" 
  128.     ohos:orientation="horizontal" 
  129.     ohos:top_margin="30vp" 
  130.     ohos:left_margin="15vp" 
  131.     ohos:right_margin="15vp"
  132.     <Button 
  133.       ohos:id="$+id:bt_save" 
  134.       ohos:height="40vp" 
  135.       ohos:width="0" 
  136.       ohos:weight="1" 
  137.       ohos:text="保存" 
  138.       ohos:text_size="20vp" 
  139.       ohos:text_color="#ffffff" 
  140.       ohos:right_margin="30vp" 
  141.       ohos:background_element="$graphic:background_main_circle" 
  142.       ohos:layout_alignment="center"/> 
  143.     <Button 
  144.       ohos:id="$+id:bt_query" 
  145.       ohos:height="40vp" 
  146.       ohos:width="0" 
  147.       ohos:weight="1" 
  148.       ohos:text="查询" 
  149.       ohos:text_size="20vp" 
  150.       ohos:text_color="#ffffff" 
  151.       ohos:right_margin="30vp" 
  152.       ohos:background_element="$graphic:background_main_circle" 
  153.       ohos:layout_alignment="center"/> 
  154.   </DirectionalLayout> 
  155.  
  156.   <DirectionalLayout 
  157.     ohos:height="match_content" 
  158.     ohos:width="match_parent" 
  159.     ohos:orientation="horizontal" 
  160.     ohos:top_margin="30vp" 
  161.     ohos:left_margin="15vp" 
  162.     ohos:right_margin="15vp"
  163.     <Button 
  164.       ohos:id="$+id:bt_regist" 
  165.       ohos:height="40vp" 
  166.       ohos:width="0" 
  167.       ohos:weight="1" 
  168.       ohos:text="注册兼停" 
  169.       ohos:text_size="20vp" 
  170.       ohos:text_color="#ffffff" 
  171.       ohos:right_margin="30vp" 
  172.       ohos:background_element="$graphic:background_main_circle" 
  173.       ohos:layout_alignment="center"/> 
  174.     <Button 
  175.       ohos:id="$+id:bt_unregist" 
  176.       ohos:height="40vp" 
  177.       ohos:width="0" 
  178.       ohos:weight="1" 
  179.       ohos:text="解除注册" 
  180.       ohos:text_size="20vp" 
  181.       ohos:text_color="#ffffff" 
  182.       ohos:right_margin="30vp" 
  183.       ohos:background_element="$graphic:background_main_circle" 
  184.       ohos:layout_alignment="center"/> 
  185.   </DirectionalLayout> 
  186.  
  187.  
  188.  
  189.   <Text 
  190.     ohos:id="$+id:tvResultQuery" 
  191.     ohos:height="match_content" 
  192.     ohos:width="match_content" 
  193.     ohos:text_size="18vp" 
  194.     ohos:text="查询结果:" 
  195.     ohos:background_element="#cccccc" 
  196.     ohos:layout_alignment="center" 
  197.     ohos:top_margin="30vp" 
  198.     ohos:padding="10vp"/> 
  199.  
  200.   <Text 
  201.     ohos:id="$+id:tvResultListener" 
  202.     ohos:height="match_content" 
  203.     ohos:width="match_content" 
  204.     ohos:text_size="18vp" 
  205.     ohos:text="兼停结果:" 
  206.     ohos:background_element="#cccccc" 
  207.     ohos:layout_alignment="center" 
  208.     ohos:top_margin="30vp" 
  209.     ohos:padding="10vp"/> 
  210.  
  211. </DirectionalLayout> 

5.圆角背景图形background_main_circle.xml文件

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  3.        ohos:shape="rectangle"
  4.     <corners 
  5.         ohos:radius="10"/> 
  6.     <solid 
  7.         ohos:color="#00aaf5"/> 
  8.  
  9. </shape> 

实现效果视频:https://harmonyos.51cto.com/show/7929

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2021-09-03 15:27:17

鸿蒙HarmonyOS应用

2021-09-23 10:00:57

鸿蒙HarmonyOS应用

2021-12-06 15:11:34

鸿蒙HarmonyOS应用

2021-08-26 09:50:06

鸿蒙HarmonyOS应用

2021-09-13 15:14:01

鸿蒙HarmonyOS应用

2022-08-31 12:48:48

TinyDBPython数据库

2023-11-24 11:11:08

Python数据库

2021-08-27 09:57:18

鸿蒙HarmonyOS应用

2022-07-14 11:31:04

SQLToolsVScode数据库

2023-12-13 08:22:45

SQLite关系型数据库

2013-02-20 14:54:03

C#.NETNDatabase

2020-05-21 11:02:00

数据库工具 CMDB

2022-05-16 07:37:58

SQL 编辑器数据库管理工具

2021-09-06 10:24:12

鸿蒙HarmonyOS应用

2020-12-11 16:37:46

数据库/新基建/全栈

2021-09-03 15:41:00

鸿蒙HarmonyOS应用

2024-03-05 18:40:15

LiteDB数据库NoSQL

2014-07-18 09:33:53

数据库数据库优化

2021-07-29 14:03:35

鸿蒙HarmonyOS应用

2022-08-10 12:21:07

PythonWebBottle
点赞
收藏

51CTO技术栈公众号