> 文档中心 > HarmonyOS数据存储之首选项(含源码)

HarmonyOS数据存储之首选项(含源码)


功能特性说明

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

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

 开发指导

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

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

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

 获取preferences实例

  createFontPreferences(context) {    globalThis.getFontPreferences = (() => {      let preferences: Promise =      dataPreferences.getPreferences(context, PREFERENCE_NAME);      return preferences;    })  }

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

保存数据

  saveChangeFontSize(fontSize:number){    globalThis.getFontPreferences().then(async (preferences)=>{      await preferences.put(KEY_APP_FONT_SIZE,fontSize);      preferences.flush();    }).catch((err)=>{      Logger.error(TAG,'put the fontSize failed,err:'+err);    });  }

读取数据

  getChangeFontSize(){    let fontSize:number =0;    const preferences=await globalThis.getFontPreferences();    fontSize = await preferences.get(KEY_APP_FONT_SIZE,fontSize);    return fontSize;  }

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

//PreferencesUtil.etsimport dataPreferences from '@ohos.data.preferences'import Logger from '../utils/Logger'const TAG = '[PreferencesUtil]';const PREFERENCE_NAME = 'myPreferences'const KEY_APP_FONT_SIZE = 'appFontSize'export class PreferencesUtil {  createFontPreferences(context) {    globalThis.getFontPreferences = (() => {      let preferences: Promise = dataPreferences.getPreferences(context, PREFERENCES_NAME);      return preferences;    });  }  saveDefaultFontSize(fontSize: number) {    globalThis.getFontPreferences().then((preferences) => {      preferences.has(KEY_APP_FONT_SIZE).then(async (isExist) => { Logger.info(TAG, 'preferences has changeFontSize is ' + isExist); if (!isExist) {   await preferences.put(KEY_APP_FONT_SIZE, fontSize);   preferences.flush(); }      }).catch((err) => { Logger.error(TAG, 'Has the value failed with err: ' + err);      });    }).catch((err) => {      Logger.error(TAG, 'Get the preferences failed, err: ' + err);    });  }  saveChangeFontSize(fontSize: number) {    globalThis.getFontPreferences().then(async (preferences) => {      await preferences.put(KEY_APP_FONT_SIZE, fontSize);      preferences.flush();    }).catch((err) => {      Logger.error(TAG, 'put the preferences failed, err: ' + err);    });  }  async getChangeFontSize() {    let fontSize: number = 0;    const preferences = await globalThis.getFontPreferences();    fontSize = await preferences.get(KEY_APP_FONT_SIZE, fontSize);    return fontSize;  }  async deleteChangeFontSize() {    const preferences: dataPreferences.Preferences = await globalThis.getFontPreferences();    let deleteValue = preferences.delete(KEY_APP_FONT_SIZE);    deleteValue.then(() => {      Logger.info(TAG, 'Succeeded in deleting the key appFontSize.');    }).catch((err) => {      Logger.error(TAG, 'Failed to delete the key appFontSize. Cause: ' + err);    });  }}export default new PreferencesUtil();

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

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

//EntryAbility.etsimport CommonConstants from '../common/constants/CommonConstants';import PreferencesUtil from '../common/database/Preferencesutil';    onCreate(want, launchParam) { hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? ''); PreferencesUtil.createFontPreferences(this.context); //设置字体默认大小 PreferencesUtil.saveDefaultFontSize(CommonConstants.SET_SIZE_NORMAL)    }

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

import CommonConstants from '../common/constants/CommonConstants';import PreferencesUtil from '../common/database/Preferencesutil';import Logger from '../common/utils/Logger';const TAG = '[IndexPage]';@Entry@Componentstruct Index {  @State message: string = 'Hello World'  @State changeFontSize:number=0;  onPageShow(){    PreferencesUtil.getChangeFontSize().then((value)=>{      this.changeFontSize=value;      Logger.info(TAG,"Get the value of changeFontSize:"+this.changeFontSize);    })  }  build() {    Row() {      Column() { Text(this.message)   .fontSize(this.changeFontSize)   .fontWeight(FontWeight.Bold)      }      .width('100%')    }    .height('100%')  }}

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

 Slider({   value: this.changeFontSize === CommonConstants.SET_SIZE_HUGE     ? CommonConstants.SET_SLIDER_MAX : this.changeFontSize,   min: CommonConstants.SET_SLIDER_MIN,   max: CommonConstants.SET_SLIDER_MAX,   step: CommonConstants.SET_SLIDER_STEP,   style: SliderStyle.InSet })   .showSteps(true)   .width('75%')   .onChange((value: number) => {     this.changeFontSize = value === CommonConstants.SET_SLIDER_MAX ? CommonConstants.SET_SIZE_HUGE : value;     PreferencesUtil.saveChangeFontSize(this.changeFontSize);   })

实现的效果:

 

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

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

读书笔记网