1.用户首选项
用户首选项(Preference)为应用提供key-value键值型的数据处理能力,支持应对持久化轻量级数据,比如小说app的字体设置背景等
1.1案例
1.index.ets
import RouterInfo from '../viewmodel/RouterInfo'
import IndexFontSizePanel from '../views/IndexFontSizePanel'
import RouterItem from '../views/RouterItem'
import PreferencesUtil from '../common/util/PreferencesUtil'
const routers: RouterInfo[] = [
new RouterInfo('pages/ImagePage', '图片查看案例'),
new RouterInfo('pages/ItemPage', '商品列表案例'),
new RouterInfo('pages/StatePage', 'Jack和他的女友案例'),
new RouterInfo('pages/PropPage', '任务列表案例'),
new RouterInfo('pages/AnimationPage', '小鱼动画案例按钮版'),
new RouterInfo('pages/AnimationPage2', '小鱼动画案例摇杆版'),
new RouterInfo('pages/LifeCirclePage', '生命周期案例1'),
new RouterInfo('pages/TestPage1', '生命周期案例2'),
new RouterInfo('pages/DocumentListPage', 'UIAbility启动模式案例'),
// new RouterInfo('pages/ShopPage', '查询商铺案例'),
//new RouterInfo('pages/TaskManagePage', '任务列表持久化案例'),
]
@Entry
@Component
struct Index {
@State message: string = '页面列表'
@State showPanel: boolean = true
@Provide fontSize: number = 16
async aboutToAppear() {
this.fontSize = await PreferencesUtil.getPreferenceValue('MyPreferences', 'IndexFontSize', 16) as number
}
build() {
Column() {
// 顶部标题
this.Title()
// 导航列表
this.RouterList()
// 字体修改面板
if (this.showPanel) {
IndexFontSizePanel()
.transition({
translate: { y: 115 }
})
}
}
.width('100%')
.height('100%')
}
@Builder
Title() {
Row() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.height(80)
Image($r('app.media.ic_public_settings'))
.width(30)
.onClick(() => {
animateTo({ duration: 500, curve: Curve.EaseOut }, () => this.showPanel = !this.showPanel)
})
}
.justifyContent(FlexAlign.SpaceAround)
.width('100%')
}
@Builder
RouterList() {
List({ space: 15 }) {
ForEach(
routers,
(router, index) => {
ListItem() {
RouterItem({ r: router, i: index + 1 })
}
}
)
}
.layoutWeight(1)
.alignListItem(ListItemAlign.Center)
.width('100%')
}
}
2.view/IndexFontSizePanel
import PreferencesUtil from '../common/util/PreferencesUtil'
@Component
export default struct IndexFontSizePanel {
@Consume fontSize: number
fontSizLabel: object = {
14: '小',
16: '标准',
18: '大',
20: '特大',
}
build() {
Column() {
Text(this.fontSizLabel[this.fontSize]).fontSize(20)
Row({ space: 5 }) {
Text('A').fontSize(14).fontWeight(FontWeight.Bold)
Slider({
min: 14,
max: 20,
step: 2,
value: this.fontSize
})
.showSteps(true)
.trackThickness(6)
.layoutWeight(1)
.onChange(val => {
// 修改字体大小
this.fontSize = val
// 写入Preferences
PreferencesUtil.putPreferenceValue('MyPreferences', 'IndexFontSize', val)
})
Text('A').fontSize(20).fontWeight(FontWeight.Bold)
}.width('100%')
}
.width('100%')
.padding(15)
.backgroundColor('#fff1f0f0')
.borderRadius(20)
}
}
3.common/util/PreferencesUtil
import preferences from '@ohos.data.preferences';
class PreferencesUtil{
prefMap: Map<string, preferences.Preferences> = new Map()
async loadPreference(context, name: string){
try { // 加载preferences
let pref = await preferences.getPreferences(context, name)
this.prefMap.set(name, pref)
console.log('testTag', `加载Preferences[${name}]成功`)
} catch (e) {
console.log('testTag', `加载Preferences[${name}]失败`, JSON.stringify(e))
}
}
async putPreferenceValue(name: string, key: string, value: preferences.ValueType){
if (!this.prefMap.has(name)) {
console.log('testTag', `Preferences[${name}]尚未初始化!`)
return
}
try {
let pref = this.prefMap.get(name)
// 写入数据
await pref.put(key, value)
// 刷盘
await pref.flush()
console.log('testTag', `保存Preferences[${name}.${key} = ${value}]成功`)
} catch (e) {
console.log('testTag', `保存Preferences[${name}.${key} = ${value}]失败`, JSON.stringify(e))
}
}
async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType){
if (!this.prefMap.has(name)) {
console.log('testTag', `Preferences[${name}]尚未初始化!`)
return
}
try {
let pref = this.prefMap.get(name)
// 读数据
let value = await pref.get(key, defaultValue)
console.log('testTag', `读取Preferences[${name}.${key} = ${value}]成功`)
return value
} catch (e) {
console.log('testTag', `读取Preferences[${name}.${key} ]失败`, JSON.stringify(e))
}
}
}
const preferencesUtil = new PreferencesUtil()
export default preferencesUtil as PreferencesUtil
2.关系型数据库
关系型数据库(RDB)是基于SQLite组件提供的本地数据库,用于管理应用中的结构化数据,例如记账本,备忘录
2.1初始化数据库
2.2增删改数据
2.3查询数据
import relationalStore from '@ohos.data.relationalStore';
import TaskInfo from '../viewmodel/TaskInfo';
class TaskModel {
private rdbStore: relationalStore.RdbStore
private tableName: string = 'TASK'
/**
* 初始化任务表
*/
initTaskDB(context){
// 1.rdb配置
const config = {
name: 'MyApplication.db',
securityLevel: relationalStore.SecurityLevel.S1
}
// 2.初始化SQL语句
const sql = `CREATE TABLE IF NOT EXISTS TASK (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
FINISHED bit
)`
// 3.获取rdb
relationalStore.getRdbStore(context, config, (err, rdbStore) => {
if(err){
console.log('testTag', '获取rdbStore失败!')
return
}
// 执行Sql
rdbStore.executeSql(sql)
console.log('testTag', '创建task表成功!')
// 保存rdbStore
this.rdbStore = rdbStore
})
}
/**
* 查询任务列表
*/
async getTaskList(){
// 1.构建查询条件
let predicates = new relationalStore.RdbPredicates(this.tableName)
// 2.查询
let result = await this.rdbStore.query(predicates, ['ID', 'NAME', 'FINISHED'])
// 3.解析查询结果
// 3.1.定义一个数组,组装最终的查询结果
let tasks: TaskInfo[] = []
// 3.2.遍历封装
while(!result.isAtLastRow){
// 3.3.指针移动到下一行
result.goToNextRow()
// 3.4.获取数据
let id = result.getLong(result.getColumnIndex('ID'))
let name = result.getString(result.getColumnIndex('NAME'))
let finished = result.getLong(result.getColumnIndex('FINISHED'))
// 3.5.封装到数组
tasks.push({id, name, finished: !!finished})
}
console.log('testTag', '查询到数据:', JSON.stringify(tasks))
return tasks
}
/**
* 添加一个新的任务
* @param name 任务名称
* @returns 任务id
*/
addTask(name: string): Promise<number>{
return this.rdbStore.insert(this.tableName, {name, finished: false})
}
/**
* 根据id更新任务状态
* @param id 任务id
* @param finished 任务是否完成
*/
updateTaskStatus(id: number, finished: boolean) {
// 1.要更新的数据
let data = {finished}
// 2.更新的条件
let predicates = new relationalStore.RdbPredicates(this.tableName)
predicates.equalTo('ID', id)
// 3.更新操作
return this.rdbStore.update(data, predicates)
}
/**
* 根据id删除任务
* @param id 任务id
*/
deleteTaskById(id: number){
// 1.删除的条件
let predicates = new relationalStore.RdbPredicates(this.tableName)
predicates.equalTo('ID', id)
// 2.删除操作
return this.rdbStore.delete(predicates)
}
}
let taskModel = new TaskModel();
export default taskModel as TaskModel;