HarmonyOS鸿蒙Next中Preference在App启动Abililty的onCreate里面执行调用会抛异常
HarmonyOS鸿蒙Next中Preference在App启动Abililty的onCreate里面执行调用会抛异常
我发现如果在App启动的时候在Ability的onCreate方法里面立刻执行SP的存储或者读取操作会有异常,
```typescript
export class StorageUtils {
static async putValue(key: string, value: any, context: any) {
if (context) {
let promise = await dataStorage.getPreferences(context, 'mystore')
promise.put(key, value)
promise.flush()
} else {
throw new Error("StorageUtils:putValue error");
}
}
static async getValueByKey(key: string, defaultValue: any, context: any): Promise {
if (context) {
let promise = await dataStorage.getPreferences(context, 'mystore')
let value = promise.get(key, defaultValue)
promise.flush()
return value
} else {
throw new Error("StorageUtils:getValueByKey error");
}
}
}
例如这个demo,会抛异常:Error: StorageUtils:getValueByKey error
更多关于HarmonyOS鸿蒙Next中Preference在App启动Abililty的onCreate里面执行调用会抛异常的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
你的代码中,判断context不存在,就抛出你日志中的异常,在oncreate中调用StorageUtils时,将其他context传过去,就不会有问题了
更多关于HarmonyOS鸿蒙Next中Preference在App启动Abililty的onCreate里面执行调用会抛异常的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,Preference
的调用如果在Ability
的onCreate
方法中执行,可能会抛出异常。这是因为Preference
依赖于系统的上下文环境,而onCreate
方法执行时,上下文环境可能尚未完全初始化。建议将Preference
的调用移至onStart
或onActive
方法中,确保上下文环境已准备就绪,从而避免异常。