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

文章目录

1、概述

用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。当用户希望有一个全局唯一存储的地方,可以采用用户首选项来进行存储。

官方文档地址:通过用户首选项实现数据持久化-应用数据持久化-ArkData(方舟数据管理)-应用框架 - 华为HarmonyOS开发者 (huawei.com)

2、运行机制
复制代码
<font style="color:rgba(0, 0, 0, 0.9);">用户程序通过ArkTS接口调用用户首选项读写对应的数据文件。开发者可以将用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。</font>
3、约束条件
  • 因为Preferences实例会加载到内存中,所以存储的数据应该是轻量级别的,建议存储的数据不超过一万条。
  • 数据key键为string类型,要求非空,并且长度不超过1024个字节。
  • value值为string类型,可以为空,长度不超过1610241024。
4、接口说明
接口名称 描述
getPreferencesSync(context: Context, options: Options): Preferences 获取Preferences实例。该接口存在异步接口。
putSync(key: string, value: ValueType): void 将数据写入Preferences实例,可通过flush将Preferences实例持久化。该接口存在异步接口。
hasSync(key: string): boolean 检查Preferences实例是否包含名为给定Key的存储键值对。给定的Key值不能为空。该接口存在异步接口。
getSync(key: string, defValue: ValueType): ValueType 获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue。该接口存在异步接口。
deleteSync(key: string): void 从Preferences实例中删除名为给定Key的存储键值对。该接口存在异步接口。
flush(callback: AsyncCallback): void 将当前Preferences实例的数据异步存储到用户首选项持久化文件中。
on(type: 'change', callback: Callback): void 订阅数据变更,订阅的数据发生变更后,在执行flush方法后,触发callback回调。
off(type: 'change', callback?: Callback): void 取消订阅数据变更。
deletePreferences(context: Context, options: Options, callback: AsyncCallback): void 从内存中移除指定的Preferences实例。若Preferences实例有对应的持久化文件,则同时删除其持久化文件。
5、开发步骤
5.1、导入模块
plain 复制代码
import preferences from '@ohos.data.preferences'
5.2、获取preference实例
plain 复制代码
private  PREFERENCES_NAME: string = 'preferneces_name';
private dataPreference;
private context = getContext(this);

async aboutToAppear(){
 await preferences.getPreferences(this.context,this.PREFERENCES_NAME)
    .then((data) => {
      this.dataPreference = data;
      console.info(this.LOGTAG,"success in getting prefernec")
  }).catch((err) => {
     console.info(this.LOGTAG,'failed to get preferences ,cause:'+ err);
   });
5.3、写入数据
plain 复制代码
Button("写入")
  .width('50%')
  .type(ButtonType.Capsule)
  .onClick(() => {
    this.dataPreference.put('pre_key', 'put avalue').then(() => {
      this.message = '写入成功'
      console.info(this.LOGTAG, 'put seccess')
    }).catch((err) => {
      console.info(this.LOGTAG, 'put failed,reason ;' + err);
    });
  });
5.4、读取数据
plain 复制代码
Button("读取")
  .width('50%')
  .margin({top:50})
  .type(ButtonType.Capsule)
  .onClick(() => {
    this.dataPreference.get('pre_key','').then((data) =>{
      this.message = data.toString();
      console.info(this.LOGTAG,'get success,data'+data)
    }).catch((err) => {
      console.info(this.LOGTAG,'get failed ,reason:'+ err)
    })
  })
5.5、删除数据
plain 复制代码
Button("删除")
  .width('50%')
  .margin({ top: 10 })
  .type(ButtonType.Capsule)
  .onClick(() => {
    this.dataPreference.delete('pre_key').then(() => {
      console.info(this.LOGTAG, 'delete success' )
    }).catch((err) => {
      console.info(this.LOGTAG, 'delete failed ,reason:' + err)
    })
  })
5.6、数据持久化
plain 复制代码
Button("数据持久化")
  .width('50%')
  .margin({ top: 10 })
  .type(ButtonType.Capsule)
  .onClick(() => {
    // @ts-ignore
    this.dataPreference.flush((err: BusinessError) => {
      if (err) {
        console.info(this.LOGTAG, 'flush error code:' + err.code + 'message:' + err.message)
        return;
      }
      console.info(this.LOGTAG, 'flush success')
    })
  })
5.7、删除指定文件
plain 复制代码
Button("删除指定文件")
  .width('50%')
  .margin({ top: 10 })
  .type(ButtonType.Capsule)
  .onClick(() => {
    preferences.deletePreferences(this.context,this.PREFERENCES_NAME,(err) =>{
      if (err) {
        console.info(this.LOGTAG, 'deletePreferences error code:' + err.code + 'message:' + err.message)
        return;
      }
      console.info(this.LOGTAG, 'deletePreferences success')
    })
  })
6、文件代码
plain 复制代码
import preferences from '@ohos.data.preferences'


@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  private LOGTAG = 'log_cat';
  private PREFERENCES_NAME: string = 'preferneces_name';
  private dataPreference: preferences.Preferences;
  private context = getContext(this);

  async aboutToAppear() {
    await preferences.getPreferences(this.context, this.PREFERENCES_NAME)
      .then((data) => {
        this.dataPreference = data;
        console.info(this.LOGTAG, "success in getting prefernec")
      }).catch((err) => {
        console.info(this.LOGTAG, 'failed to get preferences ,cause:' + err);
      });
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(32)
          .width('100%')

        Button("写入")
          .width('50%')
          .type(ButtonType.Capsule)
          .onClick(() => {
            this.dataPreference.put('pre_key', 'put avalue').then(() => {
              this.message = '写入成功'
              console.info(this.LOGTAG, 'put seccess')
            }).catch((err) => {
              console.info(this.LOGTAG, 'put failed,reason ;' + err);
            });
          });

        Button("读取")
          .width('50%')
          .margin({ top: 10 })
          .type(ButtonType.Capsule)
          .onClick(() => {
            this.dataPreference.get('pre_key', '').then((data) => {
              this.message = data.toString();
              console.info(this.LOGTAG, 'get success,data' + data)
            }).catch((err) => {
              console.info(this.LOGTAG, 'get failed ,reason:' + err)
            })
          })

        Button("删除")
          .width('50%')
          .margin({ top: 10 })
          .type(ButtonType.Capsule)
          .onClick(() => {
            this.dataPreference.delete('pre_key').then(() => {
              console.info(this.LOGTAG, 'delete success')
            }).catch((err) => {
              console.info(this.LOGTAG, 'delete failed ,reason:' + err)
            })
          })

        Button("数据持久化")
          .width('50%')
          .margin({ top: 10 })
          .type(ButtonType.Capsule)
          .onClick(() => {
            // @ts-ignore
            this.dataPreference.flush((err: BusinessError) => {
              if (err) {
                console.info(this.LOGTAG, 'flush error code:' + err.code + 'message:' + err.message)
                return;
              }
              console.info(this.LOGTAG, 'flush success')
            })
          })

        Button("删除指定文件")
          .width('50%')
          .margin({ top: 10 })
          .type(ButtonType.Capsule)
          .onClick(() => {
            preferences.deletePreferences(this.context, this.PREFERENCES_NAME, (err) => {
              if (err) {
                console.info(this.LOGTAG, 'deletePreferences error code:' + err.code + 'message:' + err.message)
                return;
              }
              console.info(this.LOGTAG, 'deletePreferences success')
            })
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}
相关推荐
ysu_03143 分钟前
PINNs的参数反演——从“正问题”到“逆问题”的工程改造
人工智能·pytorch·深度学习·mcmc·参数反演·逆问题·darcy流
桃西西呀5 分钟前
限速 30 和限速 80 只差一个数字,卷积网络怎么分得清?
人工智能·深度学习·llm
爱吃苹果的日记本5 分钟前
数据结构第四课—线性表Linear List
数据结构·学习
昌原的儿子LEO12 分钟前
ARM 汇编核心知识点总结
嵌入式硬件·学习
Ray Wang18 分钟前
Context上下文工程
python·学习·ai编程
百里香酚兰19 分钟前
【Unity学习笔记】如何把粉色Prefab还原
笔记·学习·unity
索端阳39 分钟前
ARM Day02 学习总结:ARM汇编基础核心知识点梳理
汇编·学习·arm
马剑威(威哥爱编程)1 小时前
【共创稿事节】HarmonyOS 7 互动卡片实战:摇一摇触发静态转动态,前景元素出框
华为·harmonyos
贾伟康1 小时前
【HarmonyOS 7新能力|029】3DGS工程封装:把接入逻辑放进可维护的分层结构
harmonyos·arkts·三维重建·3dgs·harmonyos 7
马剑威(威哥爱编程)1 小时前
【共创稿事节】HarmonyOS 7 闪控窗实战:标准悬浮窗、侧边栏暂存与闪控球一键切换
华为·harmonyos