鸿蒙应用开发:数据持久化
最近在搞公司项目用到了鸿蒙端的数据持久化,特来跟大家分享一下。
在鸿蒙开发中,可以使用以下几个包来实现数据的持久化处理:
- Data Ability
通过数据能力组件,开发者可以实现复杂的数据操作,包括增、删、改、查等功能。它允许不同的应用共享数据,并提供了统一的数据访问接口。
- SQLite
这是一个轻量级的关系型数据库,适用于本地存储。开发者可以使用 SQL 语句进行数据管理,支持事务处理,适合需要复杂查询的场景。
- Preferences
适合存储简单的配置信息和用户偏好。通过键值对的方式存取数据,非常方便,尤其是在需要保存少量数据时。
- File System
直接操作文件系统,允许读写文件。这种方法灵活性高,适合存储大文件或非结构化数据,比如图片、音频等。
本次分享主要以用户首选项为例:在登陆页面输入个人信息后,点击“配置”后保存输入数据并且跳转到下一个页面,在第二个页面显示用户在登陆页输入的信息,并且支持登录页与显示页的数据同步。此外,登录页“退出”按钮绑定了应用关闭功能。
PreferenceModel.ets
import dataPreferences from '@ohos.data.preferences';
import promptAction from '@ohos.promptAction';
import { BusinessError } from '@ohos.base';
import showToast from './ShowToast';
let context = getContext(this);
let TAG:string = 'preference';
// 自定义用户首选项类
export class PreferenceModel {
static preferences: dataPreferences.Preferences | null = null;
/**
* 初始化用户首选项类
*/
public static initPre(){
let options: dataPreferences.Options = { name: 'myStore.db' };
PreferenceModel.preferences = dataPreferences.getPreferencesSync(context, options);
}
/**
* 写入并保存数据
* @param name - 键名
* @param data - 键值
*/
public static async writeData(name:string,data:string) {
// Check whether the data is null.
let isDataNull = PreferenceModel.checkData(data);
if (isDataNull) {
return;
}
// The data is inserted into the preferences database if it is not empty.
PreferenceModel.preferences.putSync(name,data);
// 使用flush方法将preferences实例的数据存储到持久化文件,调用用户首选项实例的flush接口
await PreferenceModel.preferences.flush();
// PreferenceModel.putPreference(name,data);
showToast('保存成功!');
}
/**
* 获取数据,返回字符串类型结果
* @param name - 键名
*/
public static getPreference(name:string) {
let isExist: boolean = PreferenceModel.preferences.hasSync(name);
if (isExist) {
console.info(TAG + "The key 'startup' is contained.");
let value: dataPreferences.ValueType = PreferenceModel.preferences.getSync(name, 'default');
return value.toString().replace(/^"|"$/g, '');
} else {
console.info(TAG + "The key 'startup' dose not contain.");
showToast('该值不存在!');
}
}
}
Register.ets
import router from '@ohos.router';
import { PreferenceModel } from '../common/PreferenceModel';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import window from '@ohos.window';
@Entry
@Component
struct Register {
@State ip:string = '';
@State port:string = '';
@State username:string = '';
@State password:string = '';
@State port_ftp:string = '';
@State isFocused: boolean = false;
context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
aboutToAppear(): void {
// 设置不显示导航栏和状态栏
window.getLastWindow(this.context).then((data) => {
data.setWindowSystemBarEnable([]).then(() => {
console.debug('Succeeded in setting the system bar to be invisible.');
});
});
PreferenceModel.initPre()
this.ip = PreferenceModel.hasPreference('register-ip')
? (PreferenceModel.getPreference('register-ip')).toString()
: '10.0.1.182';
this.port = PreferenceModel.hasPreference('register-port')
? (PreferenceModel.getPreference('register-port')).toString()
: '1883';
this.username = PreferenceModel.hasPreference('register-username')
? (PreferenceModel.getPreference('register-username')).toString()
: 'username';
this.password = PreferenceModel.hasPreference('register-password')
? (PreferenceModel.getPreference('register-password')).toString()
: 'password';
this.port_ftp = PreferenceModel.hasPreference('register-port-ftp')
? (PreferenceModel.getPreference('register-port-ftp')).toString()
: '21';
}
build() {
Stack({ alignContent: Alignment.TopStart }) {
// 中间的内容部分
Column({ }) {
Column({ space:20 }){
TextInput({text: this.ip})
.backgroundColor('#FFFFFF')
.focusable(this.isFocused)
.textAlign(TextAlign.Center)
.onChange((value:string)=>{
this.ip = value
})
.onClick(()=>{
this.isFocused = true
})
Divider()
.margin({top:-25})
TextInput({text: this.port})
.backgroundColor('#FFFFFF')
.focusable(this.isFocused)
.textAlign(TextAlign.Center)
.onChange((value:string)=>{
this.port = value
})
.onClick(()=>{
this.isFocused = true
})
Divider()
.margin({top:-25})
TextInput({text: this.username})
.backgroundColor('#FFFFFF')
.focusable(this.isFocused)
.textAlign(TextAlign.Center)
.onChange((value:string)=>{
this.username = value
})
.onClick(()=>{
this.isFocused = true
})
Divider()
.margin({top:-25})
TextInput({text: this.password})
.backgroundColor('#FFFFFF')
.focusable(this.isFocused)
.textAlign(TextAlign.Center)
.onChange((value:string)=>{
this.password = value
})
.onClick(()=>{
this.isFocused = true
})
Divider()
.margin({top:-25})
TextInput({text: this.port_ftp})
.backgroundColor('#FFFFFF')
.focusable(this.isFocused)
.textAlign(TextAlign.Center)
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.onChange((value:string)=>{
this.port_ftp = value
})
.onClick(()=>{
this.isFocused = true
})
Divider()
.margin({top:-25})
}
.width('40%')
.height('60%')
.margin({top:px2vp(200)})
Row({space:80}){
Text("配置")
.fontFamily('Source Han Sans CN-Regular')
.fontSize(24)
.fontColor('#262B2F')
.fontWeight(400)
.textAlign(TextAlign.Center)
.width(130)
.height(60)
.borderRadius(10)
.backgroundColor('#c1e6c6')
.onClick(()=>{
PreferenceModel.writeData('register-ip',JSON.stringify(this.ip))
PreferenceModel.writeData('register-port',JSON.stringify(this.port))
PreferenceModel.writeData('register-username',JSON.stringify(this.username))
PreferenceModel.writeData('register-password',JSON.stringify(this.password))
PreferenceModel.writeData('register-port-ftp',JSON.stringify(this.port_ftp))
router.pushUrl({url: 'pages/Index'}).then(()=>{
}).catch((err: BusinessError) => {
})
})
Text("退出")
.fontFamily('Source Han Sans CN-Regular')
.fontSize(24)
.fontColor('#262B2F')
.fontWeight(400)
.textAlign(TextAlign.Center)
.width(130)
.height(60)
.borderRadius(10)
.backgroundColor('#c1e6c6')
.onClick(async ()=>{
this.context.terminateSelf()
})
}
.width(500)
.height('30%')
.justifyContent(FlexAlign.Center)
}
.width('94.6%')
.height('92.2%')
.backgroundColor('#FFFFFF')
.borderRadius(30)
.margin({left:"2.7%",top:"7.8%"})
.alignItems(HorizontalAlign.Center)
}
.width('100%')
.height('100%')
.backgroundColor('#2d2736')
}
}
Index.ets
import { PreferenceModel } from '../common/PreferenceModel';
@Entry
@Component
struct Index {
@State message: string[] = [];
aboutToAppear(): void {
PreferenceModel.initPre()
this.message.push(PreferenceModel.getPreference('register-ip').toString());
this.message.push(PreferenceModel.getPreference('register-port').toString());
this.message.push(PreferenceModel.getPreference('register-username').toString());
this.message.push(PreferenceModel.getPreference('register-password').toString());
this.message.push(PreferenceModel.getPreference('register-port-ftp').toString());
}
build() {
Row() {
Column() {
ForEach(this.message, (item, index)=>{
Text(item)
.fontSize(50)
.fontWeight(FontWeight.Bold)
})
}
.width('100%')
}
.height('100%')
}
}
效果
项目已上传gitee,感兴趣的家人不妨给个星星⭐