• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lightweight Data Store Development
2
3## When to Use
4
5The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the Preferences APIs.
6
7## Available APIs
8
9The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the string, Boolean, integer, long integer, float, double, or string array type.
10
11**Creating a Preferences Instance**
12
13Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance.
14
15**Table 1** API for creating a Preferences instance
16
17| Class| Method| Description|
18| --- | ----- | ----|
19| PreferencesHelper | static std::shared_ptr<Preferences> GetPreferences(const std::string &path, int &errCode); | Creates a **Preferences** instance. <br>**path**: storage path of the application data.<br>**errCode**: error code.<br>Return value: **Preferences** instance created.|
20
21**Writing Data**
22
23Call the **put()** method to add or modify data in a **Preferences** instance.
24
25**Table 2** APIs for writing data
26
27| Class| Method| Description|
28| --- | ----- | ----|
29| Preferences | int PutInt(const std::string &key, int value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
30| Preferences | int PutString(const std::string &key, const std::string &value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
31| Preferences | int PutBool(const std::string &key, bool value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
32| Preferences | int PutLong(const std::string &key, int64_t value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
33| Preferences | int PutFloat(const std::string &key, float value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
34| Preferences | int PutDouble(const std::string &key, double value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
35| Preferences | int PutStringSet(const std::string &key, const std::set\<std::string\> &value); | **key**: key of the data to write. It cannot be empty.<br>**value**: value of the data to write.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
36
37**Reading Data**
38
39Call the **get()** method to read data from a **Preferences** instance.
40
41**Table 3** APIs for reading data
42
43| Class| Method| Description|
44| --- | ----- | ----|
45| Preferences | int GetInt(const std::string &key, const int defValue = 0); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
46| Preferences | std::string GetString(const std::string &key, const std::string &defValue = {}); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
47| Preferences | bool GetBool(const std::string &key, const bool defValue = false); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
48| Preferences | float GetFloat(const std::string &key, const float defValue = 0); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
49| Preferences | double GetDouble(const std::string &key, const double defValue = 0); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
50| Preferences | int64_t GetLong(const std::string &key, const int64_t defValue = 0); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
51| Preferences | std::set\<std::string\> GetStringSet(const std::string &key, const std::set\<std::string\> &defValue = {}); | **key**: key of the data to read. It cannot be empty.<br>**defValue**: default value to return if the operation fails or the value does not exist.<br>Return value: value obtained.|
52
53**Storing Data Persistently**
54
55Call the **Flush()** or **FlushSync()** method to write the cached data back to its text file for persistent storage.
56
57**Table 4** APIs for data persistence
58
59| Class| Method| Description|
60| --- | ----- | ----|
61| Preferences | void Flush(); | Writes data in the **Preferences** instance back to its file through an asynchronous thread.|
62| Preferences | int FlushSync(); | Writes data in the **Preferences** instance back to its file through a synchronous thread.|
63
64**Observing Data Changes**
65
66Specify **PreferencesObserver** as the callback to subscribe to data changes. When the value of the subscribed key is changed and the **flush()** method is executed, **PreferencesObserver** will be invoked.
67
68**Table 5** APIs for observing data changes
69
70| Class| Method| Description|
71| --- | ----- | ----|
72| Preferences | void RegisterObserver(std::shared_ptr<PreferencesObserver> preferencesObserver); | Subscribes to data changes. <br>**preferencesObserver**: callback invoked to return the data changes.|
73| Preferences | void UnRegisterObserver(std::shared_ptr<PreferencesObserver> preferencesObserver); | Unsubscribes from data changes. <br>**preferencesObserver**: callback used to report data changes.|
74
75**Deleting Data**
76
77Use the following APIs to delete a **Preferences** instance or data file.
78
79**Table 6** APIs for deleting data
80
81| Class| Method| Description|
82| --- | ----- | ----|
83| PreferencesHelper | int DeletePreferences(const std::string &path); | Deletes a **Preferences** instance from the memory and deletes its file from the device. <br>**path**: storage path of the application data.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
84| PreferencesHelper | int RemovePreferencesFromCache(const std::string &path); | Deletes a **Preferences** instance from the memory. <br>**path**: storage path of the application data.<br>Return value: Returns **0** if the operation is successful; returns the error code otherwise.|
85
86## How to Develop
87
881.  Import the Preferences module and related header files to the development environment.
89
90    ``` C++
91    Header file path: //distributeddatamgr_appdatamgr/interfaces/innerkits/native_preferences/include
92    ```
93
942.  Create a **Preferences** instance.
95
96    Read the specified file and load its data to the **Preferences** instance for data operations.
97
98    ``` C++
99    int errCode = E_OK;
100    Preferences pref = PreferencesHelper::GetPreferences(PREF_TEST_PATH + "test.xml", errCode); // PREF_TEST_PATH must be the application sandbox path.
101    EXPECT_EQ(errCode, E_OK);
102    ```
103
104
1053.  Write data.
106
107    Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance.
108
109    ```C++
110    pref->PutString("test", "remove");
111    ```
112
1134.  Read data.
114
115    Use the **get()** method of the **Preferences** class to read data.
116
117    ``` C++
118    std::string ret = pref->GetString("test", "defaultValue");
119    EXPECT_EQ(ret, "remove");
120    ```
121
122
1235. Store data persistently.
124
125   Use the **Flush()** or **FlushSync()** method to flush data in the **Preferences** instance to its file.
126
127    ```C++
128    int err = pref->FlushSync();
129    EXPECT_EQ(ret, E_OK);
130    ```
131
1326. Subscribe to data changes.
133
134    Specify **PreferencesObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** or **flushSync()** method is executed, **PreferencesObserver** will be invoked. Unregister the **PreferencesObserver** when it is no longer required.
135
136    Customize a class to implement the **PreferencesObserver**:
137    ``` C++
138    class PreferencesObserverCounter : public PreferencesObserver {
139    public:
140    virtual ~PreferencesObserverCounter();
141    void OnChange(Preferences &preferences, const std::string &key) override;
142
143        std::atomic_int notifyTimes;
144        static const std::vector<std::string> NOTIFY_KEYS_VECTOR;
145    };
146
147    PreferencesObserverCounter::~PreferencesObserverCounter() {}
148
149    void PreferencesObserverCounter::OnChange(Preferences &preferences, const std::string &key)
150    {
151        for (auto it = NOTIFY_KEYS_VECTOR.cbegin(); it != NOTIFY_KEYS_VECTOR.cend(); it++) {
152            if (key.compare(*it)) {
153                notifyTimes++;
154                break;
155            }
156        }
157    }
158
159    const std::vector<std::string> PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = { PreferencesTest::KEY_TEST_INT_ELEMENT,
160        PreferencesTest::KEY_TEST_LONG_ELEMENT, PreferencesTest::KEY_TEST_FLOAT_ELEMENT,
161        PreferencesTest::KEY_TEST_BOOL_ELEMENT, PreferencesTest::KEY_TEST_STRING_ELEMENT };
162    ```
163
164    Subscribe to data changes and invoke the callback:
165    ``` C++
166    std::shared_ptr<PreferencesObserver> counter =
167        std::make_shared<PreferencesObserverCounter>();
168    pref->RegisterObserver(counter); // Register a callback to return data changes.
169
170    pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test");
171    pref->Flush(); // Trigger the onChanged callback of the counter.
172    EXPECT_EQ(static_cast<PreferencesObserverCounter *>(counter.get())->notifyTimes, 1);
173
174    /* same value */
175    pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2);
176    pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test");
177    pref->Flush();
178    EXPECT_EQ(static_cast<PreferencesObserverCounter *>(counter.get())->notifyTimes, 2);
179
180    pref->UnRegisterObserver(counter); // Unregister the callback for data changes.
181    ```
182
183
1847.  Delete the specified file.
185
186    Delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
187
188    ``` C++
189    pref = nullptr;
190    int ret = PreferencesHelper::DeletePreferences("/data/test/test");
191    EXPECT_EQ(ret, E_OK);
192    ```
193