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

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Pandas统计每行数据中的空值的方法示例

《Pandas统计每行数据中的空值的方法示例》处理缺失数据(NaN值)是一个非常常见的问题,本文主要介绍了Pandas统计每行数据中的空值的方法示例,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是空值?为什么要统计空值?准备工作创建示例数据统计每行空值数量进一步分析www.chinasem.cn处

C语言中位操作的实际应用举例

《C语言中位操作的实际应用举例》:本文主要介绍C语言中位操作的实际应用,总结了位操作的使用场景,并指出了需要注意的问题,如可读性、平台依赖性和溢出风险,文中通过代码介绍的非常详细,需要的朋友可以参... 目录1. 嵌入式系统与硬件寄存器操作2. 网络协议解析3. 图像处理与颜色编码4. 高效处理布尔标志集合

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

关于MongoDB图片URL存储异常问题以及解决

《关于MongoDB图片URL存储异常问题以及解决》:本文主要介绍关于MongoDB图片URL存储异常问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录MongoDB图片URL存储异常问题项目场景问题描述原因分析解决方案预防措施js总结MongoDB图

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类