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

相关文章

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

SpringBoot3.X 整合 MinIO 存储原生方案

《SpringBoot3.X整合MinIO存储原生方案》本文详细介绍了SpringBoot3.X整合MinIO的原生方案,从环境搭建到核心功能实现,涵盖了文件上传、下载、删除等常用操作,并补充了... 目录SpringBoot3.X整合MinIO存储原生方案:从环境搭建到实战开发一、前言:为什么选择MinI

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

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

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