数据持久化就是将内存数据通过文件或者数据库的方式保存到设备中。HarmonyOS提供两两种持久化方案:
Preferences
提供了获取实例、读、取、删对应操作的方法:
getPreferences(context,name)
:获取Preferences
实例,name
是存储的文件名;get(k)
:通过key获取value值;getAll()
:获取文件所有的值;put(k,v)
:添加值,同一个key会将之前的值覆盖掉,需要通过flush()
刷新到文件中;delete(k)
:通过key删除对应的value值;clear()
:删除所有的存储值。注意:以上方法都是异步的。
通常会在EntryAbility#onCreate()
方法中创建实例,其中context
便是EntryAbility
的上下文,获取preferences
实例就可以对数据增删改查操作。
// 导入包
import dataPreferences from '@ohos.data.preferences'
// 获取实例
let preferences = dataPreferences.getPreferences(context, this.preferencesName)
下面对preferences
进行封装,基本思路:
在获取preferences
实例后会将其保存单例中,这个单例是GlobalContext
,方便后期可以通过单例直接获取实例;由于get()
返回值类型是不确定性,定义一个联合类型的别名ValueType
来接收。
const TAG = "PreferencesUtils"
// 默认文件名,可以在构造函数进行修改
const PREFERENCES_NAME = 'yiPreferences'
const KEY_PREFERENCES = "preferences"
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;
export class PreferencesUtils{
// preferences的文件名
private preferencesName: string = PREFERENCES_NAME
// 用于获取preferences实例的key值,保存到单例中
private keyPreferences: string = KEY_PREFERENCES
constructor(name: string = PREFERENCES_NAME, keyP: string = KEY_PREFERENCES) {
this.preferencesName = name
this.keyPreferences = keyP
}
createPreferences(context: Context): Promise<dataPreferences.Preferences> {
let preferences = dataPreferences.getPreferences(context, this.preferencesName)
GlobalContext.getContext().setObject(this.keyPreferences, preferences)
return preferences
}
getPreferences(): Promise<dataPreferences.Preferences> {
return GlobalContext.getContext().getObject(KEY_PREFERENCES) as Promise<dataPreferences.Preferences>
}
async get(key: string, def?: ValueType): Promise<ValueType> {
return (await this.getPreferences()).get(key, def)
}
async getAll(): Promise<Object> {
let preferences = await this.getPreferences()
return preferences.getAll()
}
async put(key: string, value: ValueType): Promise<void> {
let promise = await this.getPreferences().then(async (p) => {
await p.put(key, value)
p.flush();
}).catch((err)=>{
Logger.d(TAG, err)
})
return promise
}
async delete(key: string): Promise<void> {
return (await this.getPreferences()).delete(key)
}
async clear(): Promise<void> {
return (await this.getPreferences()).clear()
}
}
export default new PreferencesUtils()
在EntryAbility#onCreate()
方法初始化:
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
PreferencesUtils.createPreferences(this.context)
}
}
GlobalContext
export default class GlobalContext {
private constructor() { }
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
通过异步async
和await
来直接获取操作结果,也可以在then
方法回调中获取结果。
@Component
@Entry
struct PreferencesPage {
@State text: string = ""
aboutToAppear() {
PreferencesUtils.put("username", "Harden")
PreferencesUtils.put("age", 28)
PreferencesUtils.put("isStaff", true)
}
build() {
Column() {
Text(this.text)
.width('100%')
.height(60)
Row() {
Button("get")
.onClick(async () => {
this.text = await PreferencesUtils.get('username') as string
})
Button("getAll")
.onClick(async () => {
this.getAll()
})
Button("put")
.onClick(async () => {
await PreferencesUtils.put("username", "Kobe")
await PreferencesUtils.put("age", 28)
await PreferencesUtils.put("isStaff", false)
this.getAll()
})
Button("delete")
.onClick(async () => {
await PreferencesUtils.delete("isStaff")
this.getAll()
})
Button("clear")
.onClick(async () => {
await PreferencesUtils.clear()
this.getAll()
})
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
}
async getAll() {
let v = await PreferencesUtils.getAll() as Object
this.text = JSON.stringify(v)
}
}