鸿蒙开发 distributedKVStore 存储数据无效问题

背景

在开发鸿蒙时, 使用 distributedKVStore.KVManager 分布式键值数据库储存数据时, 发现存储的数据, 重启 app 就获取不到了

代码

typescript 复制代码
import distributedKVStore from '@ohos.data.distributedKVStore'

/**
 * 分布式键值数据库 管理器
 * 使用 SingleKVStore, 数据不对设备进行区分
 * 数据库配置已固定, 后期如有需要再提供更多配置
 * 提供读写方法
 * 对 Promise的使用可能不成熟, 待进一步学习后改进
 */

// 类型别名
type BooleanCallback = (Boolean) => string;

export default class KeyStorageManager {
  private config: distributedKVStore.KVManagerConfig;
  // 只能包含字母数字或者下划线, 否则会报错
  private storeId: string;
  private kvManager: distributedKVStore.KVManager;
  private kvStorage: distributedKVStore.SingleKVStore;
  private options = {
    createIfMissing: true, // 当数据库文件不存在时是否创建数据库,默认创建
    encrypt: false, // 设置数据库文件是否加密,默认不加密
    backup: false, // 设置数据库文件是否备份,默认备份
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建的数据库类型,默认为多设备协同数据库
    securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库安全级别
  };

  constructor(config: distributedKVStore.KVManagerConfig, storeId: string) {
    this.config = config;
    this.storeId = storeId;

    try {
       this.kvManager = distributedKVStore.createKVManager(this.config);
    } catch (e) {
      console.error(`创建 KVManager 失败. Code: ${e.code}, message: ${e.message}`)
    }
  }

  private createKVStore(callback: Homework.Callback<Boolean>) {
      if (this.kvStorage) {
        callback(true);
      } else {
        this.kvManager.getKVStore(this.storeId, this.options, (err, store) => {
          if (err) {
            callback(false);
            return;
          }

          this.kvStorage = store as distributedKVStore.SingleKVStore;
          callback(true);
        });
      }
  }

  getData<T>(key: string): Promise<T> {
    return new Promise((resolve: Function, reject: Function) => {
      this.createKVStore((isSuccess) => {
        if (this.kvStorage) {
          this.kvStorage.get(key).then((value: string) => {
            let json = JSON.parse(value);
            resolve(json);
          }).catch((e) => {
            console.error(`获取 value 失败. Code: ${e.code}, message: ${e.message}`)
            reject(e);
          });
        }
      })
    });
  }

  putData(key: string, value: string): Promise<void> {
    return new Promise((resolve: Function, reject: Function) => {
      this.createKVStore((isSuccess) => {
        if (this.kvStorage) {
          this.kvStorage.put(key, value);
          resolve();
        } else {
          reject(new Error("kvStorage 不存在"));
        }
      });
    });
  }

  closeStore(): Promise<void> {
    if (this.kvManager) {
      return this.kvManager.closeKVStore(this.config.bundleName, this.storeId);
    }

    return new Promise((reject: Function) => {
      reject(new Error("关闭 kvStorage 失败"));
    });
  }

  deleteStore(): Promise<void> {
    if (this.kvManager) {
      return this.kvManager.deleteKVStore(this.config.bundleName, this.storeId);
    }

    return new Promise((reject: Function) => {
      reject(new Error("删除 kvStorage 失败"));
    });
  }
}

问题

使用了模拟器, 模拟器需要设置才会保留数据

解决方法

编辑项目模块的 configrations => 勾选 keep Application data 即可

相关推荐
世人万千丶42 分钟前
Flutter 框架跨平台鸿蒙开发 - 鸿蒙版本五子棋游戏应用
学习·flutter·游戏·华为·harmonyos·鸿蒙
梁山好汉(Ls_man)1 小时前
鸿蒙_ArkTS解决Duplicate function implementation错误
开发语言·华为·typescript·harmonyos·鸿蒙
autumn20052 小时前
Flutter 框架跨平台鸿蒙开发 - 连连看游戏应用
flutter·华为·harmonyos
浮芷.3 小时前
Flutter 框架跨平台鸿蒙开发 - flutter版本样式的美食菜谱应用
flutter·harmonyos·美食
Swift社区3 小时前
鸿蒙游戏开发踩坑实录
华为·harmonyos
小雨天気.4 小时前
Flutter 框架跨平台鸿蒙开发 - 生活中的书法练习应用开发文档
flutter·生活·harmonyos
AI_零食5 小时前
Flutter 框架跨平台鸿蒙开发 - 鸿蒙麻将游戏应用
学习·flutter·游戏·华为·交互·harmonyos
互联网散修5 小时前
鸿蒙原生实战:智感握姿 – 左右手自动适配新闻列表
华为·harmonyos·手持握姿检测
独特的螺狮粉6 小时前
Flutter 框架跨平台鸿蒙开发 - 睡眠白噪音开发纪录
flutter·华为·harmonyos·鸿蒙
提子拌饭1336 小时前
Flutter 框架跨平台鸿蒙开发 - 商用项目看板应用
flutter·华为·harmonyos