Self study Hongmeng application development (23) - store a small amount of data locally

Posted by raahool_16 on Sat, 15 Jan 2022 07:57:54 +0100

The lightweight preference database in Hongmeng system is mainly used to save some common configurations of applications. The data is stored in local files and loaded in memory, so the access speed is faster and more efficient.

Let's look at the demo video of this article first:

Preference

The first is to realize the basic function.

public class MainAbilitySlice extends AbilitySlice {    static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x12345, "MainAbilitySlice");    static final String preferenceFile = "preferences";    static final String counterKey = "ClickCounter";    int clickCounter = 0;    @Override    public void onStart(Intent intent) {        super.onStart(intent);        super.setUIContent(ResourceTable.Layout_ability_main);        readCounter();        Text hello = (Text)findComponentById(ResourceTable.Id_text_hello);        hello.setClickedListener(new Component.ClickedListener() {            public void onClick(Component component) {                clickCounter++;                try {                    ohos.global.resource.ResourceManager resManager = getContext().getResourceManager();                    String hello_msg = resManager.getElement(ResourceTable.String_hello_message).getString();                    new ToastDialog(getContext())                            .setText(hello_msg + "X" + clickCounter)                            .setAlignment(LayoutAlignment.BOTTOM)                            .show();                } catch (IOException | NotExistException | WrongTypeException e) {                    e.printStackTrace();                }            }        });

Line 5 of the code defines a clickCounter to represent the number of clicks, and its initial value is 0. In [Hello, Hongmeng!!!] The 14th line of the click event processing code of will perform an incremental operation on clickCounter. When each click is added by 1.

If you just go to this step, you will still count from 1 after each program restart. In order not to lose the results of each operation, we first prepare the following two functions to read data from the preference database and write data to the preference database:

private void readCounter(){    DatabaseHelper databaseHelper = new DatabaseHelper(getContext());    Preferences preferences = databaseHelper.getPreferences(preferenceFile);    clickCounter = preferences.getInt(counterKey, 0);}
private void writeCounter(){    DatabaseHelper databaseHelper = new DatabaseHelper(getContext());    Preferences preferences = databaseHelper.getPreferences(preferenceFile);    preferences.putInt(counterKey, clickCounter);}

The preferenceFile and contentkey used by these two methods are respectively used to represent the file name of the preference database and the key value of the output data. They have been defined in lines 3 and 4 of the first section of code. This approach is easier to manage and better readable when the size of the program becomes larger.

After the method is ready, we can call the readCounter in the onStart method of the Slice class, like the first line of code tenth, and then call writeCounter in the onStop method of the Slice class, just like the third row in the code below. ​​​​​​​

public void onStop() {    writeCounter();    super.onStop();    // Print a log hilog info(label, "MainAbilitySlice.onStop!");}

This ensures that the counter value is saved every time the program exits and read out every time it starts.

It should be noted that the lightweight preference database is a non relational database, which is not suitable for storing a large amount of data. It is often used to operate the data in the form of key value pairs.

Reference documents

https://developer.harmonyos.com/cn/docs/documentation/doc-guides/database-preference-guidelines-0000000000030083

New book Introduction

Actual Python design pattern It's a new book recently published by the author. Please pay more attention!

This book uses the standard GUI toolkit tkinter of Python to illustrate 23 design patterns one by one through executable examples. On the one hand, it can make readers understand the application scenarios and problems to be solved of each design pattern in real software development; On the other hand, by explaining the solution process of these problems, readers can understand how to judge the advantages and disadvantages of using design patterns when writing code, and make rational use of design patterns.

Readers who are interested in design patterns and hope to use them with learning can quickly cross the threshold from understanding to application through this book; Readers who want to learn Python GUI programming can use the examples in this book as a reference for design and development; Readers who use Python language for image analysis and data processing can quickly build their own system architecture based on the examples in this book.

Think this article is helpful? Please share it with more people.

Focus on WeChat official account, object oriented thinking, and learn every day easily!

Object oriented development, object-oriented thinking!

Topics: Design Pattern