【鸿蒙学习笔记】通过用户首选项实现数据持久化

官方文档:通过用户首选项实现数据持久化

目录标题

使用场景

  1. Preferences会将该数据缓存在内存中,当用户读取的时候,能够快速从内存中获取数据,当需要持久化时可以使用flush接口将内存中的数据写入持久化文件中。
  2. Preferences会随着存放的数据量越多而导致应用占用的内存越大,因此,Preferences不适合存放过多的数据,也不支持通过配置加密,适用的场景一般为应用保存用户的个性化设置(字体大小,是否开启夜间模式)等。

第1步:源码

cpp 复制代码
import { common } from '@kit.AbilityKit';
import dataPreferences from '@ohos.data.preferences';

@Entry
@Component
struct Index {
  @State changeFontSize: number = 16;
  // 上下文
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
  //1. 获取preference
  private preferencesInstance: dataPreferences.Preferences = dataPreferences.getPreferencesSync(this.context, { name: 'myStore' });

  aboutToAppear(): void {
    //4. 页面打开后,直接从preference中获取上一次的数据
    let result = this.preferencesInstance.getSync("fontSizeKey", 16)
    this.changeFontSize = Number(result)
  }

  build() {
    Column() {
      Row({ space: 10 }) {
        Text('当前进度一览').fontSize(this.changeFontSize)
      }.margin(20)

      Slider({
        value: this.changeFontSize,
        min: 14,
        max: 22,
        step: 2,
        style: SliderStyle.InSet
      })
        .showSteps(true)
        .width('75%')
        .onChange(async (value: number) => {
          this.changeFontSize = value
          //2. 保存数据
          this.preferencesInstance.putSync('fontSizeKey', this.changeFontSize);
          //3. 持久化数据
          this.preferencesInstance.flush()
        })

    }.backgroundColor('#f2f3f5').width('100%').height('100%')
  }
}

第2步:启动模拟器

第3步:启动entry

第6步:操作

样例2

cpp 复制代码
import dataPreferences from '@ohos.data.preferences';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index_preferences2 {
  @State message: string = 'Hello World';
  private context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext
  private preferencesInstance: dataPreferences.Preferences =  dataPreferences.getPreferencesSync(this.context, { name: 'myStore' });

  aboutToAppear(): void {
    let result = this.preferencesInstance.getSync("messageKey","默认值1")
    this.message = String(result)
  }

  build() {
    Row() {
      Column() {
        TextInput({text:this.message}).fontSize(20).fontWeight(FontWeight.Bold)
          .onChange((value)=>{
            this.message = value
          })
        Button("保存")
          .onClick(()=>{
            this.preferencesInstance.putSync('message', this.message);
            this.preferencesInstance.flush()
            AlertDialog.show({message:"保存成功"})
          })

        Button("读取").onClick(() => {
          let result = this.preferencesInstance.getSync("messageKey","默认值2")
          this.message = String(result)//获取到的数据不是String,需要转换一下
          AlertDialog.show({message:this.message})
          console.log("test",result)
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
相关推荐
技术路线图2 分钟前
鸿蒙系统支付宝更新教程:华为应用市场操作步骤详解
华为·harmonyos
段一凡-华北理工大学3 分钟前
工业领域的Hadoop架构学习~系列文章03:MapReduce编程模型深度解读
大数据·人工智能·hadoop·学习·架构·高炉炼铁·高炉智能化
GitCode官方3 分钟前
开源鸿蒙跨平台直播|15场·10大框架|首期:跨平台不是“权衡之选“,而是基础设施
人工智能·华为·开源·harmonyos·atomgit
互联网散修6 分钟前
鸿蒙实战:图像滤镜工坊——ColorFilter 颜色矩阵与动态调节
harmonyos·图片颜色滤镜
UnicornDev11 分钟前
【Flutter x HarmonyOS 6】设置页面的UI设计
flutter·ui·华为·harmonyos·鸿蒙
元气少女小圆丶11 分钟前
SenseGlove Nova 2+Unity开发笔记3
笔记·unity·游戏引擎
bush417 分钟前
嵌入式linux学习记录三
学习
霸道流氓气质20 分钟前
Spring AI Alibaba 学习路线图:从入门到精通
人工智能·学习·spring
Engineer邓祥浩22 分钟前
宏观认知(二):AI项目落地与团队协作——吴恩达《AI for Everyone》Week2学习笔记
人工智能·笔记·学习
中屹指纹浏览器26 分钟前
隐性风控:解析指纹浏览器IP与环境参数冲突BUG及全套适配方案
经验分享·笔记