HarmonyOS学习(十五)——数据管理(四) 用户首选项封装

文章目录

1、实体类
plain 复制代码
/**
 * 定义实体类
 */
export default class AccountBean{
  id: number;
  name: string;
  price: string;
}
2、工具类封装
plain 复制代码
import dataPreference from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';

//preference的名称
const PREFERENCE_NMAE = 'pre_name';
const LOG_TAG = 'preferencesUtil';
let context = getContext(this) as common.UIAbilityContext;

export default class PreferenceUtils {


  //preference对象
  private preferences:preferences.Preferences | null = null;


  /**
   * 获取preferenced对象
   */
 async  getPreferencesFromStorage(){
   await dataPreference.getPreferences(context,PREFERENCE_NMAE).then((data) => {
      this.preferences = data
     console.info(LOG_TAG,'init preferences  success')
    }).catch((err) =>{
     console.error(LOG_TAG,'init preferences faild ,reason:'+err);
   })
  }

  /**
   * 存放preferences键值对
   * @param key
   * @param value
   */
  async putPreference(key: string,value: string){
    if (this.preferences === null){
      await this.getPreferencesFromStorage();
    }
    await this.preferences.put(key,value).then(() => {
      console.info(LOG_TAG,'put data success');
    }).catch((err) => {
      console.error(LOG_TAG,'put data failed,reason:'+err);
    })
    await this.preferences.flush();
  }

  /**
   * 获取指定key的preference的值
   * @param key
   * @returns
   */
  async getPreference(key: string){
    let result = '';
    if(this.preferences === null){
      await this.getPreferencesFromStorage();
    }
    await this.preferences.get(key,'').then((data) => {
      result = data.toString();
      console.info(LOG_TAG,'get data success, data:'+data.toString());
    }).catch((err) => {
      console.error(LOG_TAG,'get data failed,reason:'+err);
    })
    return result;
  }

  /**
   * 删除指定key的preferences
   * @param key
   */
  async deletePreference(key: string){
    if(this.preferences === null){
      await this.getPreferencesFromStorage();
    }
    await this.preferences.delete(key).then(() => {
      console.info(LOG_TAG,'delete data success');
    }).catch((err) => {
      console.error(LOG_TAG,'get data failed,reason:'+err);
    })
  }

  /**
   * 更新指定key的值
   * @param key
   * @param value
   */
  async updatePreference(key: string,value: string){
    if(this.preferences === null){
      await this.getPreferencesFromStorage();
    }
    this.deletePreference(key);
    this.putPreference(key,value);
  }
  /**
   * 数据持久化
   */
  async flushPreference(){
    if(this.preferences === null){
      await this.getPreferencesFromStorage();
    }
    await this.preferences.flush((err) => {
      if(err){
        console.info(LOG_TAG,'flush failed err.code:'+err.code + 'err message:'+err.message);
        return;
      }
      console.info(LOG_TAG,'flush success');
    })
  }

  /**
   * 删除Preferences
   */
  async  deletePreferences(){
    await preferences.deletePreferences(context,PREFERENCE_NMAE).then(() => {
      console.info(LOG_TAG,'delete  success');
    }).catch((err) => {
      console.error(LOG_TAG,'delete  failed err.code:'+err.code + 'err message:'+err.message);
    })
  }
}
3、调用实体类
plain 复制代码
import AccountBean from '../entry/AccountBean';
import preferenceUtils from '../pages/PreferenceUtils'
const PERFERENCE_KEY_NAME = 'pre_utils_name';

@Component
@Entry
struct UtilsPage {
  @State message: string = 'show messge';
  private preferenceUtils = new preferenceUtils();
  
  async aboutToAppear() {
    //初始化preferences
    await this.preferenceUtils.getPreferencesFromStorage();
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize(30)

      Button('写入数据')
        .type(ButtonType.Capsule)
        .margin({top:10})
        .onClick(() => {
         let newAccountBean: AccountBean = {id:1,name:'购物',price:'22'}
          this.preferenceUtils.putPreference(PERFERENCE_KEY_NAME,JSON.stringify(newAccountBean));
        })

      Button('读取数据')
        .type(ButtonType.Capsule)
        .margin({top:10})
        .onClick(() => {
          this.preferenceUtils.getPreference(PERFERENCE_KEY_NAME).then((resultData) => {
            this.message =  resultData;
          });
        })

      Button('修改数据')
        .type(ButtonType.Capsule)
        .margin({top:10})
        .onClick(() => {
          let newAccount: AccountBean = {id:1,name:'购物',price:'25'};
          this.preferenceUtils.updatePreference(PERFERENCE_KEY_NAME,JSON.stringify(newAccount));
        })

      Button('删除数据')
        .type(ButtonType.Capsule)
        .margin({top:10})
        .onClick(() => {
         this.preferenceUtils.deletePreference(PERFERENCE_KEY_NAME);
        })
    }
    .width('100%')
  }
}
4、效果
相关推荐
遇到困难睡大觉哈哈10 小时前
HarmonyOS 公共事件机制介绍以及多进程之间的通信实现(9000字详解)
华为·harmonyos
幽蓝计划14 小时前
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
开发语言·harmonyos
伍哥的传说14 小时前
鸿蒙系统(HarmonyOS)应用开发之实现电子签名效果
开发语言·前端·华为·harmonyos·鸿蒙·鸿蒙系统
Georgewu16 小时前
【HarmonyOS】应用开发拖拽功能详解
harmonyos
塞尔维亚大汉16 小时前
鸿蒙内核源码分析(构建工具篇) | 顺瓜摸藤调试鸿蒙构建过程
源码·harmonyos
kumalab19 小时前
HarmonyOS ArkTS卡片堆叠滑动组件实战与原理详解(含源码)
华为·harmonyos
别说我什么都不会20 小时前
【OpenHarmony】鸿蒙开发之xml2jsDemo
harmonyos
HarmonyOS_SDK1 天前
HarmonyOS免密认证方案 助力应用登录安全升级
harmonyos
zhanshuo1 天前
鸿蒙操作系统核心特性解析:从分布式架构到高效开发的全景技术图谱
harmonyos
塞尔维亚大汉1 天前
鸿蒙内核源码分析(编译过程篇) | 简单案例窥视编译全过程
源码·harmonyos