HarmonyOS学习(十四)——数据管理(三) 用户首选项

ops/2024/10/9 15:18:00/

文章目录

        • 1、概述
        • 2、运行机制
        • 3、约束条件
        • 4、接口说明
        • 5、开发步骤
          • 5.1、导入模块
          • 5.2、获取preference实例
          • 5.3、写入数据
          • 5.4、读取数据
          • 5.5、删除数据
          • 5.6、数据持久化
          • 5.7、删除指定文件
        • 6、文件代码

1、概述

用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。当用户希望有一个全局唯一存储的地方,可以采用用户首选项来进行存储。

官方文档地址:通过用户首选项实现数据持久化-应用数据持久化-ArkData(方舟数据管理)-应用框架 - 华为HarmonyOS开发者 (huawei.com)

2、运行机制
<font style="color:rgba(0, 0, 0, 0.9);">用户程序通过ArkTS接口调用用户首选项读写对应的数据文件。开发者可以将用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。</font>

3、约束条件
  • 因为Preferences实例会加载到内存中,所以存储的数据应该是轻量级别的,建议存储的数据不超过一万条。
  • 数据key键为string类型,要求非空,并且长度不超过1024个字节。
  • value值为string类型,可以为空,长度不超过1610241024。
4、接口说明
接口名称描述
getPreferencesSync(context: Context, options: Options): Preferences获取Preferences实例。该接口存在异步接口。
putSync(key: string, value: ValueType): void将数据写入Preferences实例,可通过flush将Preferences实例持久化。该接口存在异步接口。
hasSync(key: string): boolean检查Preferences实例是否包含名为给定Key的存储键值对。给定的Key值不能为空。该接口存在异步接口。
getSync(key: string, defValue: ValueType): ValueType获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue。该接口存在异步接口。
deleteSync(key: string): void从Preferences实例中删除名为给定Key的存储键值对。该接口存在异步接口。
flush(callback: AsyncCallback): void将当前Preferences实例的数据异步存储到用户首选项持久化文件中。
on(type: ‘change’, callback: Callback): void订阅数据变更,订阅的数据发生变更后,在执行flush方法后,触发callback回调。
off(type: ‘change’, callback?: Callback): void取消订阅数据变更。
deletePreferences(context: Context, options: Options, callback: AsyncCallback): void从内存中移除指定的Preferences实例。若Preferences实例有对应的持久化文件,则同时删除其持久化文件。

5、开发步骤
5.1、导入模块
import preferences from '@ohos.data.preferences'
5.2、获取preference实例
private  PREFERENCES_NAME: string = 'preferneces_name';
private dataPreference;
private context = getContext(this);async aboutToAppear(){await preferences.getPreferences(this.context,this.PREFERENCES_NAME).then((data) => {this.dataPreference = data;console.info(this.LOGTAG,"success in getting prefernec")}).catch((err) => {console.info(this.LOGTAG,'failed to get preferences ,cause:'+ err);});
5.3、写入数据
Button("写入").width('50%').type(ButtonType.Capsule).onClick(() => {this.dataPreference.put('pre_key', 'put avalue').then(() => {this.message = '写入成功'console.info(this.LOGTAG, 'put seccess')}).catch((err) => {console.info(this.LOGTAG, 'put failed,reason ;' + err);});});
5.4、读取数据
Button("读取").width('50%').margin({top:50}).type(ButtonType.Capsule).onClick(() => {this.dataPreference.get('pre_key','').then((data) =>{this.message = data.toString();console.info(this.LOGTAG,'get success,data'+data)}).catch((err) => {console.info(this.LOGTAG,'get failed ,reason:'+ err)})})
5.5、删除数据
Button("删除").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {this.dataPreference.delete('pre_key').then(() => {console.info(this.LOGTAG, 'delete success' )}).catch((err) => {console.info(this.LOGTAG, 'delete failed ,reason:' + err)})})

5.6、数据持久化
Button("数据持久化").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {// @ts-ignorethis.dataPreference.flush((err: BusinessError) => {if (err) {console.info(this.LOGTAG, 'flush error code:' + err.code + 'message:' + err.message)return;}console.info(this.LOGTAG, 'flush success')})})
5.7、删除指定文件
Button("删除指定文件").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {preferences.deletePreferences(this.context,this.PREFERENCES_NAME,(err) =>{if (err) {console.info(this.LOGTAG, 'deletePreferences error code:' + err.code + 'message:' + err.message)return;}console.info(this.LOGTAG, 'deletePreferences success')})})
6、文件代码
import preferences from '@ohos.data.preferences'@Entry
@Component
struct Index {@State message: string = 'Hello World'private LOGTAG = 'log_cat';private PREFERENCES_NAME: string = 'preferneces_name';private dataPreference: preferences.Preferences;private context = getContext(this);async aboutToAppear() {await preferences.getPreferences(this.context, this.PREFERENCES_NAME).then((data) => {this.dataPreference = data;console.info(this.LOGTAG, "success in getting prefernec")}).catch((err) => {console.info(this.LOGTAG, 'failed to get preferences ,cause:' + err);});}build() {Row() {Column() {Text(this.message).fontSize(32).width('100%')Button("写入").width('50%').type(ButtonType.Capsule).onClick(() => {this.dataPreference.put('pre_key', 'put avalue').then(() => {this.message = '写入成功'console.info(this.LOGTAG, 'put seccess')}).catch((err) => {console.info(this.LOGTAG, 'put failed,reason ;' + err);});});Button("读取").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {this.dataPreference.get('pre_key', '').then((data) => {this.message = data.toString();console.info(this.LOGTAG, 'get success,data' + data)}).catch((err) => {console.info(this.LOGTAG, 'get failed ,reason:' + err)})})Button("删除").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {this.dataPreference.delete('pre_key').then(() => {console.info(this.LOGTAG, 'delete success')}).catch((err) => {console.info(this.LOGTAG, 'delete failed ,reason:' + err)})})Button("数据持久化").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {// @ts-ignorethis.dataPreference.flush((err: BusinessError) => {if (err) {console.info(this.LOGTAG, 'flush error code:' + err.code + 'message:' + err.message)return;}console.info(this.LOGTAG, 'flush success')})})Button("删除指定文件").width('50%').margin({ top: 10 }).type(ButtonType.Capsule).onClick(() => {preferences.deletePreferences(this.context, this.PREFERENCES_NAME, (err) => {if (err) {console.info(this.LOGTAG, 'deletePreferences error code:' + err.code + 'message:' + err.message)return;}console.info(this.LOGTAG, 'deletePreferences success')})})}.width('100%').height('100%')}.height('100%')}
}

http://www.ppmy.cn/ops/123236.html

相关文章

Solidity智能合约中的事件和日志

1. Solidity 中的事件和日志概述 1.1 什么是事件&#xff1f; 在 Solidity 中&#xff0c;事件&#xff08;Event&#xff09;是一种允许智能合约与外部世界进行通信的机制。通过触发事件&#xff0c;可以记录合约执行中的关键操作&#xff0c;并将这些操作发送到链上。事件的…

JC系列CAN通信说明

目录 一、CAN协议二、指令格式三、通信接线3.1、一对一通信3.2、组网通信 四、寄存器定义五、指令说明4、读取电源电压5、读取母线电流6、读取实时速度8、读取实时位置10、读取驱动器温度11、读取电机温度12、读取错误信息32、设定电流33、设定速度35、设定绝对位置37、设定相对…

61. 环境贴图.envMap(金属效果)

环境贴图对PBR材质渲染效果影响还是比较大&#xff0c;一般渲染PBR材质的模型&#xff0c;最好设置一个合适的环境贴图。 立方体纹理加载器CubeTextureLoader TextureLoader返回TextureCubeTextureLoader返回CubeTexture 通过前面学习大家知道&#xff0c;通过纹理贴图加载器…

win11/win10/windows下快安装并使用git

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、Git 的特点&#xff1f;二、GIT安装方法1.打开GIT官网2.下载git安装程序整个安装过程基本上直接用默认选项就可以 总结 前言 提示&#xff1a;GIT介绍 GI…

【Sceneform-EQR】(手势控制器实现)通过手势事件实现在AR/VR等三维场景中的控制模型旋转、平移与缩放

在Sceneform-EQR中实现旋转平移缩放手势 实现在AR/VR等三维场景&#xff0c;通过手势控制模型节点的缩放、平移和旋转。 实现思路 实现模型旋转 Sceneform-EQR(filament\opengl)中采用右手坐标系。通过欧拉角进行旋转采用Z->Y->X的顺序&#xff0c;在这里&#xff0c;…

微信第三方开放平台接入本地消息事件接口报错问题java.security.InvalidKeyException: Illegal key size

先看报错&#xff1a; java.security.InvalidKeyException: Illegal key sizeat javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)at javax.crypto.Cipher.implInit(Cipher.java:805)at javax.crypto.Cipher.chooseProvider(Cipher.java:864)at javax.crypto.Cipher.in…

ArgoCD 与 Amazon EKS 结合实战

在当今快速发展的云原生世界中,持续部署和基础设施即代码已成为不可或缺的实践。ArgoCD 作为一个强大的 Kubernetes 持续部署工具,结合 Amazon EKS (Elastic Kubernetes Service) 这一成熟的托管 Kubernetes 服务,为开发者和运维团队提供了一个强大的组合。本文将深入探讨如…

飘香水果网站:SpringBoot实现的电子商务解决方案

1系统概述 1.1 研究背景 如今互联网高速发展&#xff0c;网络遍布全球&#xff0c;通过互联网发布的消息能快而方便的传播到世界每个角落&#xff0c;并且互联网上能传播的信息也很广&#xff0c;比如文字、图片、声音、视频等。从而&#xff0c;这种种好处使得互联网成了信息传…