零基础学鸿蒙编程-轻量级数据库
什么是轻量级数据库
轻量级数据库是一种以键值对形式保存数据的存储方式.每条数据都需要指定一个唯一键名来进行区分.可以存储布尔型、整型、字符串等基础数据类型.其特点为简单、轻量,适合保存少量简单类型的数据,不适合保存大批量或复杂类型的数据.
基础样例
1. 写入和读取数据
- java代码
public class MainAbilitySlice extends AbilitySlice {
private Preferences preferences;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
String filename = "pdb";
preferences = databaseHelper.getPreferences(filename);
findComponentById(ResourceTable.Id_writeText).setClickedListener(component -> write());
findComponentById(ResourceTable.Id_readText).setClickedListener(component -> read());
findComponentById(ResourceTable.Id_modifyText).setClickedListener(component -> modify());
findComponentById(ResourceTable.Id_delText).setClickedListener(component -> del());
}
private void write() {
preferences.putString("name", "花生皮编程");
preferences.flush();
}
private void read() {
String name = preferences.getString("name", "数据不存在");
new ToastDialog(getContext()).setText(name).show();
}
private void modify() {
preferences.putString("name", "花生皮编程2");
preferences.flush();
}
private void del() {
preferences.delete("name");
}
}
- 对应页面布局文件:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$ id:writeText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="写数据"
ohos:text_size="20fp"/>
<Text
ohos:id="$ id:readText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="读数据"
ohos:text_size="20fp"/>
<Text
ohos:id="$ id:modifyText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="修改数据"
ohos:text_size="20fp"/>
<Text
ohos:id="$ id:delText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="删除数据"
ohos:text_size="20fp"/>
</DirectionalLayout>
常用函数说明
函数名 | 用途 |
---|---|
putString | 存储字符串类型数据 |
putInt | 存储整型数据 |
putLong | 存储长整型数据 |
putFloat | 存储浮点型数据 |
putBoolean | 存储布尔值,true或false |
putStringSet | 存储字符串集合 |
delete | 删除指定键名对应的数据记录 |
clear | 清空所有存储的数据 |
apply | 修改数据后,提交保存到文件中 |
getString | 以字符串类型读取出数据 |
getInt | 以整型读取出数据 |
getLong | 以长整型读取出数据 |
getFloat | 以浮点型读取出数据 |
getBoolean | 以布尔值读取出数据 |
完整源代码
https://gitee.com/hspbc/harmonyos_demos/tree/master/preferenceDemo
零基础系列
关于我
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhfgiihk
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01