一,用户首选项简述
@ohos.data.preferences (用户首选项)
用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。
数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。
说明:
本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
具体详情查看官网,地址:
文档中心
二,常用接口介绍
- 数据保存(putString)
- 获取数据(getString)
- 是否包含指定的key(has)
- 数据持久化(flush)
- 修改数据(update)
- 删除数据(delete)
- 清空数据(clear)
三,创建单列GlobalContext,方便后期可以通过单例直接获取实例;由于get()
返回值类型是不确定性,定义一个联合类型的别名ValueType
来接收
export default class GlobalContext {private constructor() {}private static instance: GlobalContextprivate _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)}
}
四,创建PreferencesUtils工具类
import dataPreferences from '@ohos.data.preferences'
import GlobalContext from './GlobalContext'const TAG = "PreferencesUtils"
// 默认文件名,可以在构造函数进行修改
const PREFERENCES_NAME = 'dbPreferences'
const PREFERENCES_KEY = "preferences"
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;class PreferencesUtils{// preferences的文件名-数据库表名private preferencesName: string = PREFERENCES_NAME// 用于获取preferences实例的key值,保存到单例中private keyPreferences: string = PREFERENCES_KEYconstructor(name: string = PREFERENCES_NAME, key: string = PREFERENCES_KEY) {this.preferencesName = namethis.keyPreferences = key}/*** 创建首选项实例* @param context 应用上下文* @returns 数据库表名*/initPreferences(context): Promise<dataPreferences.Preferences> {let preferences = dataPreferences.getPreferences(context, this.preferencesName)GlobalContext.getContext().setObject(this.keyPreferences, preferences)return}/*** 获取首选项实例* @returns*/getPreferences(): Promise<dataPreferences.Preferences> {return GlobalContext.getContext().getObject(this.keyPreferences) as Promise<dataPreferences.Preferences>}/*** 获取数据* @param key 读取key值* @param def 函数出参* @returns*/async getString(key: string, defaultValue?: ValueType): Promise<ValueType> {//在typescript中,空字符串、数字0、null、undefined都被认为是false,其他值为trueif (!key) {return defaultValue}return (await this.getPreferences()).get(key, defaultValue)}/*** 获取全部数据* @returns*/async getAll(): Promise<Object> {let preferences = await this.getPreferences()if (!preferences) {console.debug(TAG+'--->>>[getAll] Preferences实例为空')return}return preferences.getAll()}/*** 插入数据* @param key 插入key值* @param value 存储数据* @returns*/async putString(key: string, defaultValue: ValueType): Promise<void> {let promise = await this.getPreferences().then(async preferences => {// 插入数据await preferences.put(key, defaultValue)//写入文件await preferences.flush()}).catch(error => {console.error(TAG, `code:${error.code}, message:${error.message}`)})return promise}/*** 更新指定key的值* @param key 需要更新的key* @param newValue 新的值* @returns*/async update(key:string, newValue: ValueType):Promise<void>{if (!key) {throw new Error('Key cannot be empty!');}const preferences = await this.getPreferences()if (await preferences.has(key)) {//检查key是否存在await preferences.put(key, newValue); // 更新值await preferences.flush(); // 刷新以保存更改}else {throw new Error(`Key ${key} does not exist`); // 如果key不存在,抛出错误}}/*** 删除数据* @param key 删除key的value值* @returns*/async delete(key:string):Promise<void>{return (await this.getPreferences()).delete(key).finally(async ()=>{(await this.getPreferences()).flush()})}/*** 清空数据* @returns*/async clear():Promise<void>{return (await this.getPreferences()).clear().finally(async ()=>{(await this.getPreferences()).flush()})}
}export default new PreferencesUtils()
五,在EntryAbility中onCreate()
方法初始化:
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');//TODO 方法初始化PreferencesUtils.initPreferences(this.context)}
六,在pages中使用
import PreferencesUtils from '../dbSQL/PreferencesUtils';@Entry
@Component
struct Index {@State message: string = '';aboutToAppear(){PreferencesUtils.putString('userName','张三')PreferencesUtils.putString('age','18')PreferencesUtils.putString('sex','男')}async getAll(){this.message=JSON.stringify(await PreferencesUtils.getAll())console.log('getAll', this.message)}build() {Column({space:50}) {Text(this.message).fontSize(20).margin({top:30}).fontWeight(FontWeight.Bold)Column({space:20}){Button('getAll').onClick(async ()=>{this.getAll()})Button('put').onClick(async ()=>{//插入数据key相同时,会自动修改替换value值PreferencesUtils.putString('userName','李四')PreferencesUtils.putString('age','24')PreferencesUtils.putString('sex','女')this.getAll()})Button('update').onClick(async ()=>{await PreferencesUtils.update('userName','王二麻子')await PreferencesUtils.update('age','35')await PreferencesUtils.update('sex','男')this.getAll()})Button('delete').onClick(async ()=>{await PreferencesUtils.delete('sex')this.getAll()})Button('clear').onClick(async ()=>{await PreferencesUtils.clear()this.getAll()})}.margin({top:30}).justifyContent(FlexAlign.Center)}.width('100%')}
}