HarmonyOS应用五之轻量化数据存储持久化

2024-08-23 10:28

本文主要是介绍HarmonyOS应用五之轻量化数据存储持久化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录:

    • 1、数据存储场景持久化方式
    • 2、数据存储
    • 3、数据读取
    • 4、删除数据
    • 5、应用内字体大小调节

1、数据存储场景持久化方式

  • 用户首选项(Preferences):为应用提供Key-Value键值型的数据处理能力,通常用于保存应用的配置信息。数据通过文本的形式保存在设备中,应用使用过程中会将文本中的数据全量加载到内存中,所以访问速度快、效率高,但不适合需要存储大量数据的场景。
  • 关系型数据库(RelationalStore):一种关系型数据库,以行和列的形式存储数据,广泛用于应用中的关系型数据的处理,包括一系列的增、删、改、查等接口,开发者也可以运行自己定义的SQL语句来满足复杂业务场景的需要。
  • 键值型数据库(KV-Store):一种非关系型数据库,其数据以“键值”对的形式进行组织、索引和存储,其中“键”作为唯一标识符。适合很少数据关系和业务关系的业务数据存储,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。相比于关系型数据库,更容易做到跨设备跨版本兼容。

详细介绍以及使用流程

2、数据存储

/** Copyright (c) 2022 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import { promptAction } from '@kit.ArkUI';
import { preferences } from '@kit.ArkData';
import Logger from '../common/utils/Logger';
import CommonConstants from '../common/constants/CommonConstants';
import Fruit from '../viewmodel/Fruit';let context = getContext(this);
let preference: preferences.Preferences;
let preferenceTemp: preferences.Preferences;/*** Preference model.** @param fruitData Fruit data.*/
class PreferenceModel {private fruitData: Fruit = new Fruit();/*** Read the specified Preferences persistence file and load the data into the Preferences instance.*/async getPreferencesFromStorage() {try {preference = await preferences.getPreferences(context, CommonConstants.PREFERENCES_NAME);} catch (err) {Logger.error(CommonConstants.TAG, `Failed to get preferences, Cause: ${err}`);}}/*** Deletes the specified Preferences persistence file from memory and removes the Preferences instance.*/async deletePreferences() {try {await preferences.deletePreferences(context, CommonConstants.PREFERENCES_NAME);} catch(err) {Logger.error(CommonConstants.TAG, `Failed to delete preferences, Cause: ${err}`);};preference = preferenceTemp;this.showToastMessage($r('app.string.delete_success_msg'));}/*** Save the data to the Preferences.** @param fruit Fruit data.*/async putPreference(fruit: Fruit) {if (!preference) {await this.getPreferencesFromStorage();}// The fruit name and fruit quantity data entered by the user are saved to the cached Preference instance.try {await preference.put(CommonConstants.KEY_NAME, JSON.stringify(fruit));} catch (err) {Logger.error(CommonConstants.TAG, `Failed to put value, Cause: ${err}`);}// Store the Preference instance in the preference persistence fileawait preference.flush();}/*** Get preference data.*/async getPreference() {let fruit = '';if (!preference) {await this.getPreferencesFromStorage();}try {// fruit = <string> await preference.get(CommonConstants.KEY_NAME, '');fruit = (await preference.get(CommonConstants.KEY_NAME, '')).toString();} catch (err) {Logger.error(CommonConstants.TAG, `Failed to get value, Cause: ${err}`);}// If the data is empty, a message is displayed indicating that data needs to be written.if (fruit === '') {this.showToastMessage($r('app.string.data_is_null_msg'));return;}this.showToastMessage($r('app.string.read_success_msg'));return JSON.parse(fruit);}/*** Process the data obtained from the database.*/async getFruitData() {this.fruitData = await this.getPreference();return this.fruitData;}/*** Verifies that the data entered is not empty.** @param fruit Fruit data.*/checkFruitData(fruit: Fruit) {if (fruit.fruitName === '' || fruit.fruitNum === '') {this.showToastMessage($r('app.string.fruit_input_null_msg'));return true;}return false;}/*** write data.** @param fruit  Fruit data.*/writeData(fruit: Fruit) {// Check whether the data is null.let isDataNull = this.checkFruitData(fruit);if (isDataNull) {return;}// The data is inserted into the preferences database if it is not empty.this.putPreference(fruit);this.showToastMessage($r('app.string.write_success_msg'));}/*** Popup window prompt message.** @param message Prompt message.*/showToastMessage(message: Resource) {promptAction.showToast({message: message,duration: CommonConstants.DURATION});};
}export default new PreferenceModel();

数据存储调用代码:

 await preference.put(CommonConstants.KEY_NAME, JSON.stringify(fruit));

3、数据读取

 new ButtonItemData($r('app.string.read_data_btn_text'),() => {// Get data from the preferences database.PreferenceModel.getFruitData().then((resultData: Fruit) => {if (resultData) {this.fruit = resultData;}});}),
 async getFruitData() {this.fruitData = await this.getPreference();return this.fruitData;}
 async getPreference() {let fruit = '';if (!preference) {await this.getPreferencesFromStorage();}try {// fruit = <string> await preference.get(CommonConstants.KEY_NAME, '');fruit = (await preference.get(CommonConstants.KEY_NAME, '')).toString();} catch (err) {Logger.error(CommonConstants.TAG, `Failed to get value, Cause: ${err}`);}// If the data is empty, a message is displayed indicating that data needs to be written.if (fruit === '') {this.showToastMessage($r('app.string.data_is_null_msg'));return;}this.showToastMessage($r('app.string.read_success_msg'));return JSON.parse(fruit);}

根据debug流程发现请求如下:
PreferenceModel.getFruitData()-》await this.getPreference()(异步)-》await preference.get(CommonConstants.KEY_NAME, ‘’)).toString()(异步)-》然后原路返回PreferenceModel.getFruitData()走完-》this.showToastMessage(判断里面)-》getFruitData()
在这里插入图片描述
再执行完await preference.get(CommonConstants.KEY_NAME, ‘’)).toString()(异步)返回时走了then里面已经成功拿到数据了。

4、删除数据

 new ButtonItemData($r('app.string.delete_data_file_btn_text'),() => {// Delete database files.PreferenceModel.deletePreferences();// After a database file is deleted, the corresponding data is left blank.this.fruit.fruitName = '';this.fruit.fruitNum = ''})
  async deletePreferences() {try {await preferences.deletePreferences(context, CommonConstants.PREFERENCES_NAME);} catch(err) {Logger.error(CommonConstants.TAG, `Failed to delete preferences, Cause: ${err}`);};preference = preferenceTemp;this.showToastMessage($r('app.string.delete_success_msg'));}

await preferences.deletePreferences(context, CommonConstants.PREFERENCES_NAME);是根据实例名称删除指定的实例。

参考链接

5、应用内字体大小调节

  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(StyleConstants.SLIDER_WIDTH_PERCENT).onChange(async (value: number) => {if (this.changeFontSize === 0) {this.changeFontSize = await PreferencesUtil.getChangeFontSize();this.fontSizeText = SetViewModel.getTextByFontSize(value);return;}this.changeFontSize = (value === CommonConstants.SET_SLIDER_MAX ? CommonConstants.SET_SIZE_HUGE : value);this.fontSizeText = SetViewModel.getTextByFontSize(this.changeFontSize);PreferencesUtil.saveChangeFontSize(this.changeFontSize);})

在这里插入图片描述

滑动后触发onchange方法,value值监听到值大小,然后在首选项中保存更新字体大小值;保存后走Slider函数中替换新值并页面同步改变了字体大小。

这篇关于HarmonyOS应用五之轻量化数据存储持久化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1099118

相关文章

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

MyBatisPlus如何优化千万级数据的CRUD

《MyBatisPlus如何优化千万级数据的CRUD》最近负责的一个项目,数据库表量级破千万,每次执行CRUD都像走钢丝,稍有不慎就引起数据库报警,本文就结合这个项目的实战经验,聊聊MyBatisPl... 目录背景一、MyBATis Plus 简介二、千万级数据的挑战三、优化 CRUD 的关键策略1. 查

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

MySQL之InnoDB存储引擎中的索引用法及说明

《MySQL之InnoDB存储引擎中的索引用法及说明》:本文主要介绍MySQL之InnoDB存储引擎中的索引用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1、背景2、准备3、正篇【1】存储用户记录的数据页【2】存储目录项记录的数据页【3】聚簇索引【4】二

mysql中的数据目录用法及说明

《mysql中的数据目录用法及说明》:本文主要介绍mysql中的数据目录用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、版本3、数据目录4、总结1、背景安装mysql之后,在安装目录下会有一个data目录,我们创建的数据库、创建的表、插入的

MySQL之InnoDB存储页的独立表空间解读

《MySQL之InnoDB存储页的独立表空间解读》:本文主要介绍MySQL之InnoDB存储页的独立表空间,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、独立表空间【1】表空间大小【2】区【3】组【4】段【5】区的类型【6】XDES Entry区结构【

SQLite3 在嵌入式C环境中存储音频/视频文件的最优方案

《SQLite3在嵌入式C环境中存储音频/视频文件的最优方案》本文探讨了SQLite3在嵌入式C环境中存储音视频文件的优化方案,推荐采用文件路径存储结合元数据管理,兼顾效率与资源限制,小文件可使用B... 目录SQLite3 在嵌入式C环境中存储音频/视频文件的专业方案一、存储策略选择1. 直接存储 vs