【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫 原创 精华

木棉花沈泳鑫
发布于 2021-8-16 19:46
浏览
4收藏

前言

为了更好地熟练掌握鸿蒙手机应用开发,深圳大学木棉花今天就带来轻量级偏好数据库的学习笔记,供大家更好的学习鸿蒙手机的应用开发,我们也会将所有的笔记都整理到Awesome-HarmonyOS_木棉花中,如果想要查看更多详细的学习笔记,请关注Awesome-HarmonyOS_木棉花


正文

基本概念

在学习轻量级偏好数据库之前呢,我们需要先了解一下数据库有什么作用,我们学完之后才能够学以致用。顾名思义,数据库肯定是具有存储功能的。这轻量级偏好数据库的话呢,不仅具有储存数据的功能,还具备将数据持久化的功能。应用运行时全量数据将会被加载在内存中的,使得访问速度更快,存取效率更高。如果对数据持久化,数据最终会落盘到文本文件中,建议在开发过程中减少落盘频率,即减少对持久化文件的读写次数。并且轻量级偏好数据库是将数据以键值对的形式储存到数据库中。那什么是键值对呢,值就是储存的数据内容,那键呢,就像是打开房间的钥匙,只有打开房间才能访问得到房间里的数据,而且每一个房间有且仅有一把钥匙与其配对。

创建工程

打开DevEco Studio,点击左上角的File,点击New,再选择New Project,选择Empty Ability(java) ,点击Next。
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
将工程命名为DataBase,在Project Type中选择Application,选择API 5,并且在Device Type中选择Phone选项,点击Finish,工程就创建完成了。
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区

设计UI界面

我们需要设置出两个文本、两个文本输入框,三个按钮。
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
在entry>src>main>java>resources>base>gr。aphic中增加一个文件。
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
在graphic文件右击,选择New > Graphic Resource File,并给文件命名为 background_button。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="100vp"/>
    <solid
        ohos:color="#007DFF"/>
</shape>

将其形状设置为矩形,圆角半径设置为100vp,背景颜色设置为蓝色。
同理,我们创建一个 background_text 的文件。

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <solid
        ohos:color="#FFFFFF"/>
</shape>

那么前期的准备工作就做好了,我们接下来就需要写出我们刚刚提到的两个文本、两个文本输入框,三个按钮。

<?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:orientation="vertical">

    <Text
        ohos:id="$+id:text_fruit_tag"
        ohos:height="35vp"
        ohos:width="match_parent"
        ohos:background_element="$graphic:background_text"
        ohos:layout_alignment="left"
        ohos:text="Fruit"
        ohos:text_size="85"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        ohos:text_color="#000000"
        ohos:top_margin="25vp"
        />

    <TextField
        ohos:id="$+id:text_fruit"
        ohos:height="35vp"
        ohos:width="match_parent"
        ohos:background_element="$graphic:background_text"
        ohos:layout_alignment="left"
        ohos:text="Orange"
        ohos:text_size="50"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        ohos:text_color="#000000"
        ohos:top_margin="25vp"
        ohos:basement="#000099"
        />

    <Text
        ohos:id="$+id:text_number_tag"
        ohos:height="35vp"
        ohos:width="match_parent"
        ohos:background_element="$graphic:background_text"
        ohos:layout_alignment="left"
        ohos:text="Number"
        ohos:text_size="85"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        ohos:text_color="#000000"
        ohos:top_margin="25vp"
        />

    <TextField
        ohos:id="$+id:text_number"
        ohos:height="35vp"
        ohos:width="match_parent"
        ohos:background_element="$graphic:background_text"
        ohos:layout_alignment="left"
        ohos:text="25"
        ohos:text_size="50"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        ohos:text_color="#000000"
        ohos:top_margin="25vp"
        ohos:basement="#000099"
        />

    <Button
        ohos:id="$+id:write_btn"
        ohos:width="match_parent"
        ohos:height="35vp"
        ohos:text="Write DB"
        ohos:background_element="$graphic:background_button"
        ohos:text_size="50"
        ohos:text_color="#FFFFFF"
        ohos:top_margin="25vp"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        />

    <Button
        ohos:id="$+id:read_btn"
        ohos:width="match_parent"
        ohos:height="35vp"
        ohos:text="Read DB"
        ohos:background_element="$graphic:background_button"
        ohos:text_size="50"
        ohos:text_color="#FFFFFF"
        ohos:top_margin="25vp"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        />

    <Button
        ohos:id="$+id:delete_btn"
        ohos:width="match_parent"
        ohos:height="35vp"
        ohos:text="Delete DB File"
        ohos:background_element="$graphic:background_button"
        ohos:text_size="50"
        ohos:text_color="#FFFFFF"
        ohos:top_margin="25vp"
        ohos:right_margin="20vp"
        ohos:left_margin="20vp"
        />

</DirectionalLayout>

那我们接下来就可以在java>com.example.mydatabase>slice>MainAbilitySlice中实现出数据库了。
首先需要定义数据。在MainAbilitySlice文件中,在 public class MainAbilitySlice extends AbilitySlice 的下一行定义全局变量。

    private Context context; //DatabaseHelper的构造需要传入context
    private Button buttonWrite; // 与之对应的按钮对应
    private Button buttonRead;
    private Button buttonDelete;
    private TextField textFieldFruit; //与之对应的文本输入框对应
    private TextField textFieldNumber;
    private Preferences preferences; // 定义一个数据库
    private DatabaseHelper databaseHelper; // 定义一个数据库操作的辅助类,可以辅助建立数据库
    private String filename; // 数据库指定储存的文件名
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x12345,"打印");// 定义输出控制台,可用于输出调试

接下来在onStart中初始化刚刚定义的数据与创建数据库。

context = getContext();
        buttonWrite = (Button) findComponentById(ResourceTable.Id_write_btn); // 让定义的按钮获取在xml布局中定义的按钮的id,与xml布局中的输入按钮进行绑定
        buttonRead = (Button) findComponentById(ResourceTable.Id_read_btn);// 与xml布局中的读取按钮进行绑定
        buttonDelete = (Button) findComponentById(ResourceTable.Id_delete_btn);// 与xml布局中的删除按钮进行绑定
        textFieldFruit = (TextField) findComponentById(ResourceTable.Id_text_fruit);
        textFieldNumber = (TextField) findComponentById(ResourceTable.Id_text_number);
        filename = "database"; // 将数据库的文件名初始化为database
        databaseHelper = new DatabaseHelper(context); //实例化数据库辅助类
        preferences = databaseHelper.getPreferences(filename);//实例化数据库

至此数据库就已经创建完成,接下来就是往数据库写入数据、读取数据与删除数据库。
那接下来就分别用三个不同的函数还实现这三个功能

private void Write() {
        buttonWrite.setClickedListener(new Component.ClickedListener() { //这是“Write DB”按钮的一个点击监听器
            @Override
            public void onClick(Component component) {
                String fruit = textFieldFruit.getText(); //读取输入“Fruit”文本框的数据
                try {
                    int number = Integer.parseInt(textFieldNumber.getText()); // 读取输入“Number”文本框的数据
                    preferences.putString("fruit",fruit); //将读到的Fruit的字符串写入数据库,它对应的键是fruit
                    preferences.putInt("number",number); //将读到的Number的字符串写入数据库,它对应的键是number
                    preferences.flush(); //将实例持久化
                    new ToastDialog(context).setText("Write to DB file success").show(); //这是一个文本提示框,输出提示写入数据成功
                } catch (NumberFormatException e) {
                    new ToastDialog(context).setText("Please input number in Number row").show();//输出提示在文本输入框内没有输入数据
                }
            }
        });
    }

    private void Read() {
        buttonRead.setClickedListener(new Component.ClickedListener() {//这是“Read DB”按钮的一个点击监听器
            @Override
            public void onClick(Component component) {
                String fruit = preferences.getString("fruit",""); // 在读取数据库中“fruit”对应的值,如果数据库中没有fruit这个键,那就返回空字符 可以避免程序出现异常
                int number = preferences.getInt("number",0);  //同理这在读取数据库中number对应的数值,找不到则返回0这个默认值
                String str = String.format(Locale.ENGLISH,"fruit: %s,number: %d",fruit,number);
                new ToastDialog(context).setText(str).show(); //这是在提示框中输出通过fruit和number作为键寻找到的对应的值
            }
        });
    }

    private void Delete () {
        buttonDelete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (databaseHelper.deletePreferences(filename)) { //删除文件和文件对应的Preferences单实例 删除成功返回真,失败返回假
                    preferences.clear(); // 清空数据库
                    new ToastDialog(context).setText("Delete DB file success").show(); //用ToastDialog提示删除成功
                } else
                    new ToastDialog(context).setText("Delete DB file failed").show(); //用ToastDialog提示删除失败
            }
        });
    }

记得在onStart中调用这三个函数

        Write();
        Read();
        Delete();

这是点击三个按钮之后的提示框输出的内容
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区
至此一个完整的轻量级偏好数据库就全部完成了。

结语

源码就放在附件中了,可以供大家下载之后跑一下试试看效果,感兴趣的可以一步接一步跟着编写。更多学习资料学习笔记,请关注Awesome-HarmonyOS_木棉花,这份学习笔记也会写入其中。如果有遇到什么问题,或者查找出其中的错误之处,或者能够优化代码和界面,也欢迎各位在评论区留言讨论,让我们一起学习进步!
【木棉花】:轻量级偏好数据库学习笔记--沈泳鑫-鸿蒙开发者社区

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
MyDataBase.rar 1.07M 33次下载
已于2021-8-16 19:46:15修改
8
收藏 4
回复
举报
3条回复
按时间正序
/
按时间倒序
mb609898e2cfb86
mb609898e2cfb86

很实用的文章,重新认识了数据库。

回复
2021-8-17 11:49:48
木棉花沈泳鑫
木棉花沈泳鑫

谢谢夸奖

回复
2021-8-17 16:03:15
SummerRic
SummerRic

「围观」.jpg

回复
2021-8-17 17:00:51
回复
    相关推荐