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

打印 上一主题 下一主题

主题 974|帖子 974|积分 2922

1、概述

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

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

2、运行机制

  1. <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、导入模块

  1. import preferences from '@ohos.data.preferences'
复制代码
5.2、获取preference实例

  1. private  PREFERENCES_NAME: string = 'preferneces_name';
  2. private dataPreference;
  3. private context = getContext(this);
  4. async aboutToAppear(){
  5. await preferences.getPreferences(this.context,this.PREFERENCES_NAME)
  6.     .then((data) => {
  7.       this.dataPreference = data;
  8.       console.info(this.LOGTAG,"success in getting prefernec")
  9.   }).catch((err) => {
  10.      console.info(this.LOGTAG,'failed to get preferences ,cause:'+ err);
  11.    });
复制代码
5.3、写入数据

  1. Button("写入")
  2.   .width('50%')
  3.   .type(ButtonType.Capsule)
  4.   .onClick(() => {
  5.     this.dataPreference.put('pre_key', 'put avalue').then(() => {
  6.       this.message = '写入成功'
  7.       console.info(this.LOGTAG, 'put seccess')
  8.     }).catch((err) => {
  9.       console.info(this.LOGTAG, 'put failed,reason ;' + err);
  10.     });
  11.   });
复制代码
5.4、读取数据

  1. Button("读取")
  2.   .width('50%')
  3.   .margin({top:50})
  4.   .type(ButtonType.Capsule)
  5.   .onClick(() => {
  6.     this.dataPreference.get('pre_key','').then((data) =>{
  7.       this.message = data.toString();
  8.       console.info(this.LOGTAG,'get success,data'+data)
  9.     }).catch((err) => {
  10.       console.info(this.LOGTAG,'get failed ,reason:'+ err)
  11.     })
  12.   })
复制代码
5.5、删除数据

  1. Button("删除")
  2.   .width('50%')
  3.   .margin({ top: 10 })
  4.   .type(ButtonType.Capsule)
  5.   .onClick(() => {
  6.     this.dataPreference.delete('pre_key').then(() => {
  7.       console.info(this.LOGTAG, 'delete success' )
  8.     }).catch((err) => {
  9.       console.info(this.LOGTAG, 'delete failed ,reason:' + err)
  10.     })
  11.   })
复制代码

5.6、数据持久化

  1. Button("数据持久化")
  2.   .width('50%')
  3.   .margin({ top: 10 })
  4.   .type(ButtonType.Capsule)
  5.   .onClick(() => {
  6.     // @ts-ignore
  7.     this.dataPreference.flush((err: BusinessError) => {
  8.       if (err) {
  9.         console.info(this.LOGTAG, 'flush error code:' + err.code + 'message:' + err.message)
  10.         return;
  11.       }
  12.       console.info(this.LOGTAG, 'flush success')
  13.     })
  14.   })
复制代码
5.7、删除指定文件

  1. Button("删除指定文件")
  2.   .width('50%')
  3.   .margin({ top: 10 })
  4.   .type(ButtonType.Capsule)
  5.   .onClick(() => {
  6.     preferences.deletePreferences(this.context,this.PREFERENCES_NAME,(err) =>{
  7.       if (err) {
  8.         console.info(this.LOGTAG, 'deletePreferences error code:' + err.code + 'message:' + err.message)
  9.         return;
  10.       }
  11.       console.info(this.LOGTAG, 'deletePreferences success')
  12.     })
  13.   })
复制代码
6、文件代码

  1. import preferences from '@ohos.data.preferences'
  2. @Entry@Componentstruct 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%')  }}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

冬雨财经

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表