HarmonyOS鸿蒙Next中使用kvstore持久化存储数据,应用运行的时候能正常读取,关掉再进就没了
HarmonyOS鸿蒙Next中使用kvstore持久化存储数据,应用运行的时候能正常读取,关掉再进就没了 请问使用kvstore持久化存储数据,应用运行的时候能正常读取,关掉再进就没了是怎么回事?是设置的时候有问题吗
4 回复
楼主看一下存储的时候的回调是怎样的
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
console.log("put success: " + JSON.stringify(data));
}).catch((err) => {
console.log("put err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
2. 可以监听一下数据的变化 看看有没有被改动
let kvStore;
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
});
更多关于HarmonyOS鸿蒙Next中使用kvstore持久化存储数据,应用运行的时候能正常读取,关掉再进就没了的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
如果数据库实例未正确初始化,应用关闭后KVStore实例就会被自动释放,重新进入时需要重新调用createKVManager
和getKVStore
方法获取实例。还有如果没有在UIAbility的onCreate
或页面aboutToAppear
阶段初始化数据库,会导致数据加载时机错误!
封装数据库工具类:
import { distributedKVStore } from '@kit.DistributedDataManagerKit';
class KVStoreUtil {
private kvManager: distributedKVStore.KVManager;
private kvStore: distributedKVStore.SingleKVStore;
async init() {
const context = getContext(this) as common.Context;
const config = {
bundleName: 'com.example.demo',
userInfo: distributedKVStore.UserInfo(userId: 'default')
};
this.kvManager = distributedKVStore.createKVManager(config);
const options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION
};
this.kvStore = await this.kvManager.getKVStore('myStore', options);
}
async saveData(key: string, value: string) {
await this.kvStore.put(key, value);
await this.kvStore.flush(); // 关键持久化操作
}
}
在EntryAbility的onCreate
中完成初始化:
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
AppStorage.setOrCreate('kvUtil', new KVStoreUtil());
AppStorage.get('kvUtil').init();
}
这是鸿蒙KVStore数据持久化的典型问题。数据丢失通常由以下原因导致:
- 未正确调用flush或commit同步数据到磁盘
- 应用沙箱机制导致数据路径变更
- KVStore实例未正确初始化
检查要点:
- 确保写入操作后调用kvStore.flush()
- 确认使用正确的KVManager实例
- 检查存储路径是否使用Context.getDatabaseDir()获取
典型写入流程应包含:
- kvStore.putXXX()写入数据
- kvStore.flush()强制同步
- 检查返回值确认操作成功