当前位置:   article > 正文

HarmonyOS数据存储之首选项(含源码)_harmony 数据存储工具类

harmony 数据存储工具类

功能特性说明

首选项Preferences,可以存取Key-Value结构的数据,也可持久化。

  • 因为Preferences实例会加载到内存中,建议存储的数据不超过一万条
  • 数据中的key为stirng类型,要求非空且字符长度不超过80个字节
  • 当数据中的Value为string类型时,允许为空,字符长度不超过8192个字节

 开发指导

  1. 导入preferences模块
  2. 获取preferences实例
  3. 保存数据
  4. 读取数据

导入prefrences模块,定义数据表名称和首选项常量

  1. import dataPreferences from '@ohos.data.preferences'
  2. const PREFERENCE_NAME ='myPreferences'
  3. const KEY_APP_FONT_SIZE='appFontSize'

 获取preferences实例

  1. createFontPreferences(context) {
  2. globalThis.getFontPreferences = (() => {
  3. let preferences: Promise<dataPreferences.Preferences> =
  4. dataPreferences.getPreferences(context, PREFERENCE_NAME);
  5. return preferences;
  6. })
  7. }

我们在globalThis对象中定义了一个函数getFontPreferences ,用来获取Preferences实例,该实例包括get,put,has,delete和flush等方法。

保存数据

  1. saveChangeFontSize(fontSize:number){
  2. globalThis.getFontPreferences().then(async (preferences)=>{
  3. await preferences.put(KEY_APP_FONT_SIZE,fontSize);
  4. preferences.flush();
  5. }).catch((err)=>{
  6. Logger.error(TAG,'put the fontSize failed,err:'+err);
  7. });
  8. }

读取数据

  1. getChangeFontSize(){
  2. let fontSize:number =0;
  3. const preferences=await globalThis.getFontPreferences();
  4. fontSize = await preferences.get(KEY_APP_FONT_SIZE,fontSize);
  5. return fontSize;
  6. }

在工程中,我们为了代码的管理和结构清晰方便复用,我们一般将这种常用的接口封装到一个工具类里,比如PreferencesUtil工具类里,我们整理下代码:

  1. //PreferencesUtil.ets
  2. import dataPreferences from '@ohos.data.preferences'
  3. import Logger from '../utils/Logger'
  4. const TAG = '[PreferencesUtil]';
  5. const PREFERENCE_NAME = 'myPreferences'
  6. const KEY_APP_FONT_SIZE = 'appFontSize'
  7. export class PreferencesUtil {
  8. createFontPreferences(context) {
  9. globalThis.getFontPreferences = (() => {
  10. let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, PREFERENCES_NAME);
  11. return preferences;
  12. });
  13. }
  14. saveDefaultFontSize(fontSize: number) {
  15. globalThis.getFontPreferences().then((preferences) => {
  16. preferences.has(KEY_APP_FONT_SIZE).then(async (isExist) => {
  17. Logger.info(TAG, 'preferences has changeFontSize is ' + isExist);
  18. if (!isExist) {
  19. await preferences.put(KEY_APP_FONT_SIZE, fontSize);
  20. preferences.flush();
  21. }
  22. }).catch((err) => {
  23. Logger.error(TAG, 'Has the value failed with err: ' + err);
  24. });
  25. }).catch((err) => {
  26. Logger.error(TAG, 'Get the preferences failed, err: ' + err);
  27. });
  28. }
  29. saveChangeFontSize(fontSize: number) {
  30. globalThis.getFontPreferences().then(async (preferences) => {
  31. await preferences.put(KEY_APP_FONT_SIZE, fontSize);
  32. preferences.flush();
  33. }).catch((err) => {
  34. Logger.error(TAG, 'put the preferences failed, err: ' + err);
  35. });
  36. }
  37. async getChangeFontSize() {
  38. let fontSize: number = 0;
  39. const preferences = await globalThis.getFontPreferences();
  40. fontSize = await preferences.get(KEY_APP_FONT_SIZE, fontSize);
  41. return fontSize;
  42. }
  43. async deleteChangeFontSize() {
  44. const preferences: dataPreferences.Preferences = await globalThis.getFontPreferences();
  45. let deleteValue = preferences.delete(KEY_APP_FONT_SIZE);
  46. deleteValue.then(() => {
  47. Logger.info(TAG, 'Succeeded in deleting the key appFontSize.');
  48. }).catch((err) => {
  49. Logger.error(TAG, 'Failed to delete the key appFontSize. Cause: ' + err);
  50. });
  51. }
  52. }
  53. export default new PreferencesUtil();

为了保证App启动后,页面里的字体能正常展示,我们需要在生命周期的onCreate方法里,提前保存下默认的字体大小。

这里需要主要,我用的3.1.0.100的开发工具,默认创建的工程里的EntryAbillity文件的后缀ts,会导致我们导入Util工具包报错,我是手动修了文件后缀为ets:

  1. //EntryAbility.ets
  2. import CommonConstants from '../common/constants/CommonConstants';
  3. import PreferencesUtil from '../common/database/Preferencesutil';
  4. onCreate(want, launchParam) {
  5. hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
  6. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  7. hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
  8. hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
  9. PreferencesUtil.createFontPreferences(this.context);
  10. //设置字体默认大小
  11. PreferencesUtil.saveDefaultFontSize(CommonConstants.SET_SIZE_NORMAL)
  12. }

然后我们在页面加载显示的时候,也就是触发生命周期函数onPageShow方法处,通过我们封装的工具类方法getChangeFontSize()来读取首选项中的字体配置

  1. import CommonConstants from '../common/constants/CommonConstants';
  2. import PreferencesUtil from '../common/database/Preferencesutil';
  3. import Logger from '../common/utils/Logger';
  4. const TAG = '[IndexPage]';
  5. @Entry
  6. @Component
  7. struct Index {
  8. @State message: string = 'Hello World'
  9. @State changeFontSize:number=0;
  10. onPageShow(){
  11. PreferencesUtil.getChangeFontSize().then((value)=>{
  12. this.changeFontSize=value;
  13. Logger.info(TAG,"Get the value of changeFontSize:"+this.changeFontSize);
  14. })
  15. }
  16. build() {
  17. Row() {
  18. Column() {
  19. Text(this.message)
  20. .fontSize(this.changeFontSize)
  21. .fontWeight(FontWeight.Bold)
  22. }
  23. .width('100%')
  24. }
  25. .height('100%')
  26. }
  27. }

实现字体大小调节,我们可以通过增加一个Slider控件来实现

  1. Slider({
  2. value: this.changeFontSize === CommonConstants.SET_SIZE_HUGE
  3. ? CommonConstants.SET_SLIDER_MAX : this.changeFontSize,
  4. min: CommonConstants.SET_SLIDER_MIN,
  5. max: CommonConstants.SET_SLIDER_MAX,
  6. step: CommonConstants.SET_SLIDER_STEP,
  7. style: SliderStyle.InSet
  8. })
  9. .showSteps(true)
  10. .width('75%')
  11. .onChange((value: number) => {
  12. this.changeFontSize = value === CommonConstants.SET_SLIDER_MAX ? CommonConstants.SET_SIZE_HUGE : value;
  13. PreferencesUtil.saveChangeFontSize(this.changeFontSize);
  14. })

实现的效果:

 

学习的工程源码地址 https://download.csdn.net/download/wangjianlong/87231581  

本功能初步学完,继续加油!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/299106
推荐阅读
相关标签
  

闽ICP备14008679号