• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Preferences Development
2
3> **NOTE**
4>
5> This feature is supported since API version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
6
7## When to Use
8
9Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files.
10
11Note 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 call the **Preferences** APIs to manage data.
12
13## Available APIs
14
15The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
16
17The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
18
19For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md).
20
21### Obtaining a **Preferences** Instance
22
23Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance.
24
25**Table 1** API for obtaining a **Preferences** instance
26
27| Bundle Name           | API                                                      | Description                                                        |
28| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
29| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
30
31### Processing Data
32
33Call **put()** to add or modify data in a **Preferences** instance.
34
35Call **get()** to read data from a **Preferences** instance.
36
37Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.
38
39Call **delete()** to delete the KV pair of the specified key from the **Preferences** instance.
40
41**Table 2** APIs for processing **Preferences** data
42
43| Class       | API                                                    | Description                                                        |
44| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
45| Preferences | put(key: string, value: ValueType): Promise\<void>         | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
46| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
47| Preferences | getAll(): Promise\<Object>                                  | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance.                          |
48| Preferences | delete(key: string): Promise\<void>                         | Deletes the KV pair of the specified key from the **Preferences** instance.        |
49
50
51### Storing Data Persistently
52
53Call **flush()** to write the cached data back to its text file for persistent storage.
54
55**Table 4** API for data persistence
56
57| Class       | API                 | Description                                       |
58| ----------- | ----------------------- | ------------------------------------------- |
59| Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
60
61### Observing Data Changes
62
63You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data.
64
65**Table 5** APIs for observing **Preferences** changes
66
67| Class       | API                                                      | Description          |
68| ----------- | ------------------------------------------------------------ | -------------- |
69| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
70| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes.    |
71
72### Deleting Data
73
74You can use the following APIs to delete a **Preferences** instance or data file.
75
76**Table 6** APIs for deleting **Preferences**
77
78| Bundle Name           | API                                                      | Description                                                        |
79| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
80| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void> | Deletes a **Preferences** instance from the memory and its files from the device.|
81| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory.   |
82
83## How to Develop
84
851. Import @ohos.data.preferences and related modules to the development environment.
86
87   ```js
88   import data_preferences from '@ohos.data.preferences';
89   ```
90
912. Obtain a **Preferences** instance.
92
93   Read the specified file and load its data to the **Preferences** instance for data operations.
94
95   FA model:
96
97   ```js
98   // Obtain the context.
99   import featureAbility from '@ohos.ability.featureAbility'
100   let context = featureAbility.getContext();
101
102   let preferences = null;
103   let promise = data_preferences.getPreferences(context, 'mystore');
104
105   promise.then((pref) => {
106       preferences = pref;
107   }).catch((err) => {
108       console.info("Failed to get the preferences.");
109   })
110   ```
111
112   Stage model:
113
114   ```ts
115   // Obtain the context.
116   import UIAbility from '@ohos.app.ability.UIAbility';
117   let preferences = null;
118   export default class EntryAbility extends UIAbility {
119       onWindowStageCreate(windowStage) {
120           let promise = data_preferences.getPreferences(this.context, 'mystore');
121            promise.then((pref) => {
122                preferences = pref;
123            }).catch((err) => {
124                console.info("Failed to get the preferences.");
125            })
126       }
127   }
128
129
130   ```
131
1323. Write data.
133
134   Use **preferences.put()** to write data to the **Preferences** instance.
135
136   ```js
137   let putPromise = preferences.put('startup', 'auto');
138   putPromise.then(() => {
139       console.info("Put the value of 'startup' successfully.");
140   }).catch((err) => {
141       console.info("Failed to put the value of 'startup'. Cause: " + err);
142   })
143   ```
144
1454. Read data.
146
147   Use **preferences.get()** to read data.
148
149   ```js
150   let getPromise = preferences.get('startup', 'default');
151   getPromise.then((value) => {
152       console.info("The value of 'startup' is " + value);
153   }).catch((err) => {
154       console.info("Failed to get the value of 'startup'. Cause: " + err);
155   })
156   ```
157
1585. Store data persistently.
159
160   Use **preferences.flush()** to flush data from the **Preferences** instance to its file.
161
162   ```js
163   preferences.flush();
164   ```
165
1666. Observe data changes.
167
168   Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data.
169
170   ```js
171   let observer = function (key) {
172       console.info("The key" + key + " changed.");
173   }
174   preferences.on('change', observer);
175   // The data is changed from 'auto' to 'manual'.
176   preferences.put('startup', 'manual', function (err) {
177       if (err) {
178           console.info("Failed to put the value of 'startup'. Cause: " + err);
179           return;
180       }
181       console.info("Put the value of 'startup' successfully.");
182       preferences.flush(function (err) {
183           if (err) {
184               console.info("Failed to flush data. Cause: " + err);
185               return;
186           }
187           console.info("Flushed data successfully."); // The observer will be called.
188       })
189   })
190   ```
191
1927. Delete the specified file.
193
194   Use **deletePreferences()** to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
195
196   ```js
197   let proDelete = data_preferences.deletePreferences(context, 'mystore');
198   proDelete.then(() => {
199        console.info("Deleted data successfully.");
200   }).catch((err) => {
201        console.info("Failed to delete data. Cause: " + err);
202   })
203   ```
204