HarmonyOS鸿蒙应用开发——数据持久化Preferences
作者:访客发布时间:2024-01-04分类:程序开发学习浏览:218
导读:一、封装代码1、创建Preferences2、获取Preferences实例3、删除、put、get等等importdataPreferencesfrom'@oho...
一、封装代码
- 1、创建Preferences
- 2、获取Preferences实例
- 3、删除、put、get 等等
import dataPreferences from '@ohos.data.preferences';
import Constants from "../constant/Constant"
import Logger from "./Logger"
import GlobalContext from "./GlobalContext"
let preference: dataPreferences.Preferences;
let preferenceTemp: dataPreferences.Preferences;
let context = getContext(this);
export class PreferencesUtil {
/**
* Get the specified Preferences
* 第一种方式获取
* */
static async getPreferences(): Promise<dataPreferences.Preferences> {
return await GlobalContext.getContext().getObject(Constants.KEY_PREFERENCES) as dataPreferences.Preferences
}
/**
* Get the specified Preferences
* 第二种方式获取
* */
static getPreferencesOther(context: Context): Promise<dataPreferences.Preferences> {
return new Promise<dataPreferences.Preferences>((resolved,rejected) => {
dataPreferences.getPreferences(context, Constants.KEY_PREFERENCES)
.then((res) => {
resolved(res);
})
.catch(reason => {
rejected("hello,world");
})
});
}
/**
* Read the specified Preferences persistence file and load the data into the Preferences instance.
*/
static async createPreferences(context: Context) {
try {
preference = await dataPreferences.getPreferences(context, Constants.PREFERENCES_NAME);
GlobalContext.getContext().setObject(Constants.KEY_PREFERENCES, preference)
} catch (err) {
Logger.error(Constants.TAG, `Failed to get preferences, Cause: ${err}`);
}
}
/**
* Deletes the specified Preferences persistence file from memory and removes the Preferences instance.
*/
static async deletePreferences() {
try {
await dataPreferences.deletePreferences(context, Constants.PREFERENCES_NAME);
} catch (err) {
Logger.error(Constants.TAG, `Failed to delete preferences, Cause: ${err}`);
}
preference = preferenceTemp;
}
/**
* Save the data to the Preferences.
*
* @param data.
*/
static async put(key: string, value: unknown) {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
if (typeof value === "number") {
await preference.put(key, value);
}
if (typeof value === "string") {
await preference.put(key, value);
}
if (typeof value === "boolean") {
await preference.put(key, value);
}
if (typeof value === "object") {
if (Array.isArray(value)) {
await preference.put(key, value);
} else {
await preference.put(key, JSON.stringify(value));
}
}
} catch (err) {
Logger.error("huxiubo", `Failed to put value, Cause: ${err}`);
}
// Store the Preference instance in the preference persistence file
await preference.flush();
}
/**
* Get preference data.
*/
static async get(key: string) {
let value: unknown;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.get(key, undefined).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Get custom entity data.
*/
static async getEntity(key: string) {
let value: string = '';
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = (await preference.get(key, '')).toString();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return JSON.parse(value);
}
/**
* Get an Object object that contains all key values.
*/
static async getAll() {
let value: unknown;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.getAll().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Check if the Preferences instance contains a stored key value pair named the given Key
*/
static async has(key: string) {
let value: boolean = false;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.has(key).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Delete a stored key value pair named the given Key from the Preferences instance
*/
static async delete(key: string) {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.delete(key).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
/**
* Clear all storage in this Preferences instance
*/
static async clear() {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.clear().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
/**
*Asynchronous storage of data from the current Preferences instance to the persistent file of user preferences
*/
static async flush() {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.flush().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
}
二、创建代码,在EntryAbility中的onWindowStageCreate
async onWindowStageCreate(windowStage: window.WindowStage) {
await PreferencesUtil.createPreferences(this.context)
PreferencesUtil.put("age", 10);
// put 值
PreferencesUtil.put("name", "huxiubo");
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
三、page中获取
import CommonConstants from '../common/constant/Constant'
import Logger from '../common/utils/Logger'
import { PreferencesUtil } from '../common/utils/PreferencesUtil'
import dataPreferences from '@ohos.data.preferences';
import UIAbility from '@ohos.app.ability.UIAbility';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State preference: dataPreferences.Preferences = null;
private context = getContext(this) as common.UIAbilityContext
async getPreference() {
try {
// 异步转同步使用
this.preference = await PreferencesUtil.getPreferences()
console.info(CommonConstants.TAG, `订阅首选项变化`);
this.preference.on('change',(data) => {
console.info(CommonConstants.TAG, `订阅 key : ${JSON.stringify(data)}`);
})
} catch (e) {
console.info(CommonConstants.TAG, `Failed : ${JSON.stringify(e)}`);
}
}
aboutToAppear() {
PreferencesUtil.get("age").then((value: number) => {
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
PreferencesUtil.get("name").then((value: string) => {
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
this.getPreference()
}
preferenceGet(): string {
let value = "";
PreferencesUtil.get("name").then((v: string) => {
value = v
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
return value
}
changeName() {
PreferencesUtil.put("name", "sulijing");
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.changeName()
})
}
.width('100%')
}
.height('100%')
}
}
其中可订阅数据变化
this.preference.on('change',(data) => {
console.info(CommonConstants.TAG, `订阅 key : ${JSON.stringify(data)}`);
})
四、GlobalContext
export default class GlobalContext {
private constructor() { }
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
五、Logger
/*
* Copyright (c) 2023 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 hilog from '@ohos.hilog';
const LOGGER_PREFIX: string = 'huxiubo';
class Logger {
private domain: number;
private prefix: string;
// format Indicates the log format string.
private format: string = '%{public}s, %{public}s';
/**
* constructor.
*
* @param prefix Identifies the log tag.
* @param domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF
* @param args Indicates the log parameters.
*/
constructor(prefix: string = '', domain: number = 0xFF00) {
this.prefix = prefix;
this.domain = domain;
}
debug(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
export default new Logger(LOGGER_PREFIX);
六 常量
/*
* Copyright (c) 2023 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.
*/
/**
* Style constants that can be used by all modules
*/
export default class Constants {
static readonly PREFERENCES_NAME: string = "zy";
static readonly TAG: string = "huxiubo";
static readonly KEY_PREFERENCES = "preferences"
}
👀关注公众号:Android老皮!!!欢迎大家来找我探讨交流👀
相关推荐
- 程序开发学习排行
-
- 1鸿蒙HarmonyOS:Web组件网页白屏检测
- 2HTTPS协议是安全传输,为啥还要再加密?
- 3HarmonyOS鸿蒙应用开发——数据持久化Preferences
- 4记解决MaterialButton背景颜色与设置值不同
- 5鸿蒙HarmonyOS实战-ArkUI组件(RelativeContainer)
- 6鸿蒙HarmonyOS实战-ArkUI组件(Stack)
- 7[Android][NDK][Cmake]一文搞懂Android项目中的Cmake
- 8鸿蒙HarmonyOS实战-ArkUI组件(mediaquery)
- 9鸿蒙HarmonyOS实战-ArkUI组件(GridRow/GridCol)
- 最近发表
-
- WooCommerce最好的WordPress常用插件下载博客插件模块的相关产品
- 羊驼机器人最好的WordPress常用插件下载博客插件模块
- IP信息记录器最好的WordPress常用插件下载博客插件模块
- Linkly for WooCommerce最好的WordPress常用插件下载博客插件模块
- 元素聚合器Forms最好的WordPress常用插件下载博客插件模块
- Promaker Chat 最好的WordPress通用插件下载 博客插件模块
- 自动更新发布日期最好的WordPress常用插件下载博客插件模块
- WordPress官方最好的获取回复WordPress常用插件下载博客插件模块
- Img to rss最好的wordpress常用插件下载博客插件模块
- WPMozo为Elementor最好的WordPress常用插件下载博客插件模块添加精简版