鸿蒙 harmonyos arkts 如何实现本地永久存储
鸿蒙 harmonyos arkts 如何实现本地永久存储呢?官方给我们提供的PersistentStorage持久化数据是没法实现本地存储的
要实现本地永久存储可以使用 @ohos.data.preferences
1、新建common/PreferencesUtil.ets
import preferences from '@ohos.data.preferences';
class PreferencesUtils {
// 新增数据put
async set(name: string, key: string, value: preferences.ValueType) {
try {
var context: Context = getContext(this)
const pref = await preferences.getPreferences(context, name)
// 写入数据
await pref.put(key, value)
// 刷盘
await pref.flush()
console.log('testTag', `保存preferences[${name}]成功`)
}
catch (e) {
console.log('testTag', `保存preferences[${name}]失败`, JSON.stringify(e));
}
}
// 读取数据get
async get(name: string, key: string, defaultValue: preferences.ValueType) {
// 先判断是否存在该名称的键值对
try {
var context: Context = getContext(this)
const pref = await preferences.getPreferences(context, name)
const value = await pref.get(key, defaultValue)
console.log('testTag', `读取preferences[${name}.${key}=${value}]成功`)
return value
}
catch (e) {
console.log('testTag', `读取preferences[${name}]失败`, JSON.stringify(e));
}
}
// 删除数据del
async delete(name: string, key: string) {
try {
var context: Context = getContext(this)
const pref = await preferences.getPreferences(context, name)
await pref.delete(key)
console.log('testTag', `删除preferences[${name}]成功`)
}
catch (e) {
console.log('testTag', `删除preferences[${name}]失败`, JSON.stringify(e));
}
}
}
const preferenceUtils = new PreferencesUtils()
export default preferenceUtils
2、使用PreferencesUtils实现永久存储
import { AppBar } from "../../widget/AppBar"
import PreferencesUtils from '../../common/PreferencesUtil'
@Component
export struct Cart {
@State message: string = ""
build() {
Column() {
AppBar({ title: "购物车" })
Text(this.message).fontSize(30)
Button() {
Text("设置数据").fontSize(14).fontColor(Color.White)
}.onClick(async () => {
await PreferencesUtils.set('searchPreference', 'username', '张三')
}).margin({ top: 20 })
.padding(20)
Button() {
Text("获取").fontSize(14).fontColor(Color.White)
}.onClick(async () => {
let msg = await PreferencesUtils.get('searchPreference', 'username', '')
this.message = msg.toString()
}).margin({ top: 20 }).padding(20)
Button() {
Text("修改").fontSize(14).fontColor(Color.White)
}.onClick(async () => {
await PreferencesUtils.set('searchPreference', 'username', '李四')
}).margin({ top: 20 }).padding(20)
Button() {
Text("删除").fontSize(14).fontColor(Color.White)
}.onClick(async () => {
await PreferencesUtils.delete("searchPreference","username")
}).margin({ top: 20 }).padding(20)
}.height('100%')
.width("100%")
}
}