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

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

目录标题

使用场景

  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%')
  }
}
相关推荐
宵时待雨5 分钟前
C语言笔记归纳20:文件操作
c语言·开发语言·笔记·算法
晚烛7 小时前
Flutter + OpenHarmony 导航与状态管理架构:构建可维护、可扩展、高性能的鸿蒙应用骨架
flutter·架构·harmonyos
炽烈小老头7 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
xian_wwq7 小时前
【学习笔记】数据血缘
笔记·学习·数据血缘
日更嵌入式的打工仔8 小时前
实用:嵌入式执行时间测量常用方法
笔记·单片机
map_vis_3d8 小时前
JSAPIThree LODModel 性能优化学习笔记:细节层次模型加载
笔记·学习·3d
MarkHD9 小时前
智能体在车联网中的应用:第9天 核心工具链与仿真世界:SUMO交通仿真入门——从安装到构建你的第一个虚拟十字路口
学习
lxh01139 小时前
2025/12/18 学习总结
学习
萌虎不虎9 小时前
【在鸿蒙系统中实现录制视频预览功能】
华为·音视频·harmonyos
im_AMBER9 小时前
数据结构 13 图 | 哈希表 | 树
数据结构·笔记·学习·算法·散列表