HarmonyOS持久化存储数据Preference

Preference首选项

  • 首选项:首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。

Demo记录APP首次启动

  • 通常用于首次启动后弹出隐私协议弹窗,然后记录后,下次启动不在弹窗。
  • 调用页面
ts 复制代码
import SpUtils from './utils/SpUtils'

@Entry
@Component
struct PagePreference {
  @State msg: string = ""

  onPageShow(): void {
    this.msg = "当前数据" + SpUtils.isFirst()
  }

  build() {
    Column() {


      Button("保存数据")
        .id('PagePreferenceHelloWorld')
        .margin({ top: 20 })
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          SpUtils.setFirst()
          this.msg = "保存数据"
        })

      Button("获取数据")
        .id('PagePreferenceHelloWorld')
        .margin({ top: 20 })
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.msg = "获取数据" + SpUtils.isFirst()
        })

      Button("清空数据")
        .id('PagePreferenceHelloWorld')
        .margin({ top: 20 })
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.msg = "清空数据"
          SpUtils.clearData()
        })

      Text(this.msg)
        .fontSize(25)
        .margin({ top: 20 })

    }
    .height('100%')
    .width('100%')
  }
}
  • 工具类SpUtils
ts 复制代码
import preferences from '@ohos.data.preferences'

export default class SpUtils {
  private static KEY_DATA = "key_data"
  private static SP_NAME = "data"
  private static sp: preferences.Preferences = preferences.getPreferencesSync(getContext(this), {
    name: SpUtils.SP_NAME
  })

  //设置启动状态
  static setFirst() {
    SpUtils.sp.putSync(SpUtils.KEY_DATA, false)
    SpUtils.sp.flush()
  }


  //是否首次启动
  static isFirst(): boolean {
    let data = SpUtils.sp.getSync(SpUtils.KEY_DATA, true) as boolean
    return data
  }

  //清空该表中的所有数据
  static clearData() {
    SpUtils.sp.clearSync()
    SpUtils.sp.flush()
  }
}
相关推荐
谷子在生长1 小时前
纯血鸿蒙自定义弹窗最佳实践:从「到处复制」到「一行调用」
前端·harmonyos
小魔女千千鱼9 小时前
把 Go 塞进鸿蒙PC:windows上用 c-shared 跑 2048
harmonyos
TrisighT9 小时前
Electron 跑在鸿蒙 PC 上,单窗口和多窗口内存差 800MB?我抓了 5 组数据
性能优化·electron·harmonyos
TrisighT1 天前
AI写埋点代码,35%覆盖率坑惨运营
harmonyos·arkts·arkui
Junerver4 天前
把 DevEco Code 的 HarmonyOS 开发能力装进口袋——harmonyos-dev-skill
harmonyos
程序猿追5 天前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
古德new5 天前
鸿蒙PC使用electron迁移:Joplin Electron 桌面适配全记录
华为·electron·harmonyos
世人万千丶5 天前
桌面便签小应用 - HarmonyOS ArkUI 开发实战-TextArea与Flex布局-PC版本
华为·harmonyos·鸿蒙·鸿蒙系统
慧海灵舟5 天前
AGenUI 鸿蒙端实战踩坑录:从 Column 布局消失到异步组件宽度为 0
华为·harmonyos