OpenHarmony 快速集成轻量级存储(dataPreferences)工具类

2023-12-29 18:48:38

OpenHarmony中也有类似于Android的SharedPreferences的轻量级存储,名字叫dataPreferences,这里省略介绍,直接放工具类

一.初始化

首先在EntryAbility中对dataPreferences进行初始化操作,初始化的代码如下:

import dataPreferences from '@ohos.data.preferences';

export var preferences: dataPreferences.Preferences | null = null;

  /**
   * 获取preferences实例
   */
  initPreferenceData() {
    try {
      dataPreferences.getPreferences(this.context, 'mystore', function (err, val) {
        if (err) {
          console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
          return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
      })
    } catch (err) {
      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    }
  }

将上述的initPreferenceData方法在onWindowStageCreate中进行调用

二.工具类

然后新建工具类拷贝如下代码

import { preferences } from '../entryability/EntryAbility';
import Logger from './Logger';

const TAG: string = '[PreferencesDataUtils]'

export const KEY_SN: string = "KEY_SN"

type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>

export function getPreferencesData(key: string,valueCallBack:(value:ValueType) => void, defaultValue: string = '') {

  try {
    preferences.get(key, defaultValue, (err, val) => {
      if (err) {
        Logger.error(TAG, `Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`);
        valueCallBack("")
        return;
      }
      Logger.info(TAG, `Succeeded in getting value of 'startup'. val: ${val}.`);
      valueCallBack(val)
    })
  } catch (err) {
    Logger.error(TAG, `Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`);
    valueCallBack("")
  }
}

export function putPreferencesData(key: string, value: ValueType) {
  preferences.put(key, value, (err) => {
    if (err) {
      Logger.error(TAG, `Failed to put ${key} data. Code:${err.code}, message:${err.message}`);
      return;
    }
    Logger.info(TAG, `Succeeded in putting ${key} data ${value}.`);
    try {
      preferences.flush(function (err) {
        if (err) {
          Logger.error(TAG, "Failed to flush. code =" + err.code + ", message =" + err.message);
          return;
        }
        Logger.info(TAG, "Succeeded in flushing.");
      })
    } catch (err) {
      Logger.error(TAG, "Failed to flush. code =" + err.code + ", message =" + err.message);
    }
  })
}

防止报错我这一并吧Logger工具类放在下面了

import hilog from '@ohos.hilog'

class Logger {
  private domain: number
  private prefix: string
  private format: string = "%{public}s, %{public}s"

  constructor(prefix: string) {
    this.prefix = prefix
    this.domain = 0xFF00
  }

  debug(...args: string[]) {
    hilog.debug(this.domain, this.prefix, this.format, args)
  }

  info(...args: string[]) {
    hilog.info(this.domain, this.prefix, this.format, args)
  }

  warn(...args: string[]) {
    hilog.warn(this.domain, this.prefix, this.format, args)
  }

  error(...args: string[]) {
    hilog.error(this.domain, this.prefix, this.format, args)
  }
}

export default new Logger('[FCT]')

三.调用

调用getPreferencesData方法获取值,第一个参数是key,第二个参数是value的回调

getPreferencesData(KEY_SN, value => {

})

调用putPreferencesData方法存入键值对,第一个是key,第二个是value

putPreferencesData(KEY_SN, result)

四.存储位置

我的存储位置如下:

由于有沙箱机制,所以存储位置不一定准确,可以通过搜索文件名,文件名就是前面第一步中传入的参数,我这里是mystore,然后执行如下指令全局搜索

find / -name "*mystore*"

然后查看内容,切换到mystore目录下,然后执行指令:

cat mystore

得到存储的内容

文章来源:https://blog.csdn.net/gongjdde/article/details/135291249
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。