HarmonyOS 鸿蒙Next 首选项dataPreferences实例的通用读写
HarmonyOS 鸿蒙Next 首选项dataPreferences实例的通用读写 我看了SetAppFontSize这个第一课里的示例代码,想把首选项改为通用,但没有成功,请各位老师指点,感谢!
import dataPreferences from '@ohos.data.preferences';
import { GlobalContext } from '../utils/GlobalContext';
import Logger from '../utils/Logger';
const TAG = '[PreferencesUtil]';
const PREFERENCES_NAME = 'myPreferences';
export class PreferencesUtil {
createMyPreferences(context: Context) {
let myPreferences: Function = (() => {
let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(context, PREFERENCES_NAME);
return preferences;
});
GlobalContext.getContext().setObject('getMyPreferences', myPreferences);
}
saveDefaultPreferences(PreferenceKey: string, PreferenceValue: string) {
let getMyPreferences: Function = GlobalContext.getContext().getObject(PreferenceKey) as Function;
getMyPreferences().then(async (preferences: dataPreferences.Preferences) => {
await preferences.put(PreferenceKey, PreferenceValue);
preferences.flush();
}).catch((err: Error) => {
Logger.error(TAG, 'Get the preferences failed, err: ' + err);
});
}
saveChangePreferences(PreferenceKey: string, PreferenceValue: string) {
let getMyPreferences: Function = GlobalContext.getContext().getObject(PreferenceKey) as Function;
getMyPreferences().then(async (preferences: dataPreferences.Preferences) => {
await preferences.put(PreferenceKey, PreferenceValue);
preferences.flush();
}).catch((err: Error) => {
Logger.error(TAG, 'put the preferences failed, err: ' + err);
});
}
async getChangePreferences(PreferenceKey: string) {
let PreferenceValue: string = '';
let getMyPreferences: Function = GlobalContext.getContext().getObject(PreferenceKey) as Function;
PreferenceValue = await (await getMyPreferences()).get(PreferenceKey);
return PreferenceValue;
}
async deleteChangePreferences(PreferenceKey: string) {
let getMyPreferences: Function = GlobalContext.getContext().getObject(PreferenceKey) as Function;
const preferences: dataPreferences.Preferences = await getMyPreferences();
let deleteValue = preferences.delete(PreferenceKey);
deleteValue.then(() => {
Logger.info(TAG, 'Succeeded in deleting the key appFontSize.');
}).catch((err: Error) => {
Logger.error(TAG, 'Failed to delete the key appFontSize. Cause: ' + err);
});
}
}
export default new PreferencesUtil();
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
Logger.info(TAG, 'onCreate');
GlobalContext.getContext().setObject('abilityWant', want);
PreferencesUtil.createMyPreferences(this.context);
PreferencesUtil.saveDefaultPreferences('appFontSize', CommonConstants.SET_SIZE_NORMAL.toString());
}
}
import router from '@ohos.router';
import SettingItemComponent from '../view/SettingItemComponent';
import TitleBarComponent from '../view/TitleBarComponent';
import HomeViewModel from '../viewmodel/HomeViewModel';
import CommonConstants from '../common/constants/CommonConstants';
import StyleConstants from '../common/constants/StyleConstants';
import Logger from '../common/utils/Logger';
import PreferencesUtil from '../common/database/Preferencesutil';
import SettingData from '../viewmodel/SettingData';
const TAG = '[HomePage]';
@Component
struct HomePage {
private settingArr = HomeViewModel.initSettingData();
@State changeFontSize: number = CommonConstants.SET_SIZE_NORMAL;
onPageShow() {
PreferencesUtil.getChangePreferences('appFontSize').then(value => {
this.changeFontSize = value;
Logger.info(TAG, 'Get the value of changeFontSize: ' + this.changeFontSize);
});
}
build() {
Column() {
TitleBarComponent({ isBack: false, title: $r('app.string.home_title') })
Row() {
SettingItemComponent({
setting: this.settingArr[CommonConstants.DISPLAY_INDEX],
changeFontSize: this.changeFontSize.toString(),
itemClick: () => {}
})
}
.blockBackground(StyleConstants.BLOCK_TOP_MARGIN_FIRST_PERCENT)
Row() {
SettingItemComponent({
setting: this.settingArr[CommonConstants.VOICE_INDEX],
changeFontSize: this.changeFontSize.toString(),
itemClick: () => {}
})
}
.blockBackground(StyleConstants.BLOCK_TOP_MARGIN_SECOND_PERCENT)
Row() {
this.SettingItems()
}
.blockBackground(StyleConstants.BLOCK_TOP_MARGIN_SECOND_PERCENT)
}
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.width(StyleConstants.FULL_WIDTH)
.height(StyleConstants.FULL_HEIGHT)
}
@Builder SettingItems() {
List() {
ForEach(this.settingArr.slice(CommonConstants.START_INDEX, CommonConstants.END_INDEX),
(item: SettingData, index?: Number) => {
ListItem() {
SettingItemComponent({ setting: item, changeFontSize: this.changeFontSize.toString(), itemClick: () => {
if (index === CommonConstants.SET_FONT_INDEX) {
router.pushUrl({
url: CommonConstants.SET_URL
}).catch((error: Error) => {
Logger.info(TAG, 'HomePage push error' + JSON.stringify(error));
});
}
} })
}
}, (item: SettingData) => JSON.stringify(item))
}
.divider({
strokeWidth: $r('app.float.setting_item_divider_width'),
color: $r('app.color.setting_item_divider'),
startMargin: $r('app.float.setting_item_divider_start_margin'),
endMargin: StyleConstants.DIVIDER_END_MARGIN_PERCENT
})
}
}
@Extend(Row) function blockBackground(marginTop: string) {
.backgroundColor(Color.White)
.borderRadius($r('app.float.block_background_radius'))
.margin({ top: marginTop })
.width(StyleConstants.BLOCK_WIDTH_PERCENT)
.padding({ top: $r('app.float.block_vertical_padding'), bottom: $r('app.float.block_vertical_padding') })
}
运行时,提示string与number类型不对
更多关于HarmonyOS 鸿蒙Next 首选项dataPreferences实例的通用读写的实战教程也可以访问 https://www.itying.com/category-93-b0.html
大家有遇到preferences.delete(key)
和preferences.clear()
不生效吗?
API9,模拟器调试步骤:
- 在A页面,put(‘key’,‘value’)做持久化存储;
- 在B页面,点击按钮执行先调用
get('key')
打印有值,然后执行delete('key')
或者clear()
后,再调用get('key')
时返回值为空; - 当我执行
this.context.terminateSelf()
退出应用后,再次打开应用,A页面调用get('key')
打印还有值。
补充:
更多关于HarmonyOS 鸿蒙Next 首选项dataPreferences实例的通用读写的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
changeFontSize 这个变量还是number
类型, 把value强转为number
或者SetViewModel.getTextByFontSize(number
value)
//现在是这里过不了
onPageShow() {
PreferencesUtil.getChangePreferences('appFontSize').then((value) => {
this.changeFontSize = value;
this.fontSizeText = SetViewModel.getTextByFontSize(value);
Logger.info(TAG, 'Get the value of changeFontSize: ' + this.changeFontSize);
});
}
提示这个类型不对 SetViewModel.getTextByFontSize(value)
getTextByFontSize(fontSize: number) {
let fontSizeText: Resource | string = '';
switch (fontSize) {
case CommonConstants.SET_SIZE_SMALL:
fontSizeText = $r('app.string.set_size_small');
break;
case CommonConstants.SET_SIZE_NORMAL:
fontSizeText = $r("app.string.set_size_normal");
break;
case CommonConstants.SET_SIZE_LARGE:
fontSizeText = $r("app.string.set_size_large");
break;
case CommonConstants.SET_SIZE_EXTRA_LARGE:
fontSizeText = $r("app.string.set_size_extra_large");
break;
case CommonConstants.SET_SIZE_HUGE:
fontSizeText = $r("app.string.set_size_huge");
break;
default:
fontSizeText = $r("app.string.set_size_normal");
}
return fontSizeText;
}
import preferences from '@ohos.data.preferences';
/**
* 用户首选项
*/
class PreferencesService {
private name: string = 'music';
private pref: preferences.Preferences;
/**
* 加载
* @param context
*/
async loadPreference(context){
let pref = await preferences.getPreferences(context,this.name)
let token = await pref.get('token','');
AppStorage.SetOrCreate('token',token);
this.pref = pref;
}
/**
* 写入|覆盖
* @param key
* @param value
*/
async setPreference(key: string,value: preferences.ValueType){
AppStorage.SetOrCreate(key,value);
//写入
await this.pref.put(key,value)
//刷盘
await this.pref.flush();
}
/**
* 获取
* @param key
* @param defaultValue
*/
async getPreference(key: string,defaultValue: preferences.ValueType){
return await this.pref.get(key,defaultValue);
}
/**
* 删除
* @param key
*/
async delPreference(key: string){
await this.pref.delete(key)
}
}
let preferencesService = new PreferencesService();
export default preferencesService as PreferencesService;
let playId = await preferences.getPreference('playId',0) as number;
我这里加上了`as`
您这个简洁易懂,我测试一下,非常感谢,
获取
key
:defaultValue
:
async getPreference(key: string, defaultValue: preferences.ValueType) {
return await this.pref.get(key, defaultValue);
}
getPreference要用两个参数吗?
我的理解是读取key时,得到对应key的值,preferencesService.getPreference('appFontSize')
,
对应key没有的话返回的,
写入|覆盖
key
:value
:
async setPreference(key: string, value: preferences.ValueType) {
//写入
await this.pref.put(key, value)
//刷盘
await this.pref.flush();
}
这样写入的值就支持
- number
- string
- boolean
- Array<number>
- Array<string>
- Array<boolean> 这些类型
saveDefaultPreferences(PreferenceKey:string,PreferenceValue:dataPreferences.ValueType) { let getMyPreferences: Function = GlobalContext.getContext().getObject(PreferenceKey) as Function; getMyPreferences().then((preferences: dataPreferences.Preferences) => { preferences.has(PreferenceKey).then(async (isExist: boolean) => { Logger.info(TAG, 'preferences has changeFontSize is ’ + isExist); if (!isExist) { await preferences.put(PreferenceKey, PreferenceValue); preferences.flush(); } }).catch((err: Error) => { Logger.error(TAG, 'Has the value failed with err: ’ + err); }); }).catch((err: Error) => { Logger.error(TAG, 'Get the preferences failed, err: ’ + err); }); }
我是想改为通用的首选项来用
例如,我key为ServerIpAddress时,value为‘http://xxx.xxx.xxx.xxx’
当key为appFontSize时,value就是number了
你这里保存时,就是保存为字符串的,你试一下这里改为支持保存number, 回调时,赋值时,转一下为number.
你的
getChangePreferences方法返回的字符串
key 对应的 value 有可能是 number,也会是 string,那是不是要改为 undefine?
在HarmonyOS(鸿蒙Next)中,dataPreferences
是用于轻量级数据存储的模块,适用于存储简单的键值对数据。dataPreferences
提供了通用的读写操作,支持持久化存储,适用于应用内的配置、用户偏好等场景。
写入数据:
使用 put
方法写入数据,支持 string
、number
、boolean
等基本数据类型。示例代码如下:
import dataPreferences from '@ohos.data.preferences';
let preferences = await dataPreferences.getPreferences(this.context, 'myprefs');
await preferences.put('key', 'value');
await preferences.flush();
读取数据:
使用 get
方法读取数据,需指定默认值。示例代码如下:
let value = await preferences.get('key', 'defaultValue');
删除数据:
使用 delete
方法删除指定键的数据。示例代码如下:
await preferences.delete('key');
清空数据:
使用 clear
方法清空所有数据。示例代码如下:
await preferences.clear();
dataPreferences
提供了简单的API接口,便于开发者进行数据的存储和读取操作。