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

2024-08-22 20:36

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

1、数据存储

/** 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));

2、数据的读取

 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里面已经成功拿到数据了。

3、删除数据

 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);是根据实例名称删除指定的实例。

参考链接

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



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

相关文章

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

MySQL存储过程之循环遍历查询的结果集详解

《MySQL存储过程之循环遍历查询的结果集详解》:本文主要介绍MySQL存储过程之循环遍历查询的结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言1. 表结构2. 存储过程3. 关于存储过程的SQL补充总结前言近来碰到这样一个问题:在生产上导入的数据发现

华为鸿蒙HarmonyOS 5.1官宣7月开启升级! 首批支持名单公布

《华为鸿蒙HarmonyOS5.1官宣7月开启升级!首批支持名单公布》在刚刚结束的华为Pura80系列及全场景新品发布会上,除了众多新品的发布,还有一个消息也点燃了所有鸿蒙用户的期待,那就是Ha... 在今日的华为 Pura 80 系列及全场景新品发布会上,华为宣布鸿蒙 HarmonyOS 5.1 将于 7

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L