database-preference-guidelines.md 8.8 KB
Newer Older
A
Annie_wang 已提交
1
# Preferences Development
Z
zengyawen 已提交
2

A
Annie_wang 已提交
3 4
> **NOTE**
>
A
Annie_wang 已提交
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.
A
Annie_wang 已提交
6

A
annie_wangli 已提交
7
## When to Use
Z
zengyawen 已提交
8

A
Annie_wang 已提交
9
Preferences 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.
Z
zengyawen 已提交
10

A
Annie_wang 已提交
11
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 call the **Preferences** APIs to manage data.
Z
zengyawen 已提交
12

A
Annie_wang 已提交
13
## Available APIs
Z
zengyawen 已提交
14

A
Annie_wang 已提交
15
The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
Z
zengyawen 已提交
16

A
Annie_wang 已提交
17
The 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.
A
annie_wangli 已提交
18

A
Annie_wang 已提交
19
For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md).
A
annie_wangli 已提交
20

A
Annie_wang 已提交
21
### Obtaining a **Preferences** Instance
Z
zengyawen 已提交
22

A
Annie_wang 已提交
23
Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance.
Z
zengyawen 已提交
24

A
Annie_wang 已提交
25
**Table 1** API for obtaining a **Preferences** instance
A
annie_wangli 已提交
26

27
| Bundle Name           | API                                                      | Description                                                        |
A
Annie_wang 已提交
28 29
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
A
annie_wangli 已提交
30

A
Annie_wang 已提交
31
### Processing Data
Z
zengyawen 已提交
32

A
Annie_wang 已提交
33
Call **put()** to add or modify data in a **Preferences** instance.
Z
zengyawen 已提交
34

A
Annie_wang 已提交
35
Call **get()** to read data from a **Preferences** instance.
A
annie_wangli 已提交
36

A
Annie_wang 已提交
37 38
Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.

A
Annie_wang 已提交
39 40 41
Call **delete()** to delete the KV pair of the specified key from the **Preferences** instance.

**Table 2** APIs for processing **Preferences** data
A
Annie_wang 已提交
42 43 44 45 46

| Class       | API                                                    | Description                                                        |
| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| 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.|
| 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.|
A
Annie_wang 已提交
47 48
| Preferences | getAll(): Promise\<Object>                                  | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance.                          |
| Preferences | delete(key: string): Promise\<void>                         | Deletes the KV pair of the specified key from the **Preferences** instance.        |
A
annie_wangli 已提交
49

Z
zengyawen 已提交
50

A
Annie_wang 已提交
51
### Storing Data Persistently
Z
zengyawen 已提交
52

A
Annie_wang 已提交
53
Call **flush()** to write the cached data back to its text file for persistent storage.
Z
zengyawen 已提交
54

A
annie_wangli 已提交
55
**Table 4** API for data persistence
Z
zengyawen 已提交
56

A
Annie_wang 已提交
57 58 59
| Class       | API                 | Description                                       |
| ----------- | ----------------------- | ------------------------------------------- |
| Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
Z
zengyawen 已提交
60

A
Annie_wang 已提交
61
### Observing Data Changes
Z
zengyawen 已提交
62

A
Annie_wang 已提交
63
You 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.
Z
zengyawen 已提交
64

A
Annie_wang 已提交
65
**Table 5** APIs for observing **Preferences** changes
Z
zengyawen 已提交
66

A
Annie_wang 已提交
67 68
| Class       | API                                                      | Description          |
| ----------- | ------------------------------------------------------------ | -------------- |
A
Annie_wang 已提交
69 70
| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes.    |
A
annie_wangli 已提交
71

A
Annie_wang 已提交
72
### Deleting Data
Z
zengyawen 已提交
73

A
Annie_wang 已提交
74
You can use the following APIs to delete a **Preferences** instance or data file.
A
annie_wangli 已提交
75

A
Annie_wang 已提交
76
**Table 6** APIs for deleting **Preferences**
A
annie_wangli 已提交
77

78
| Bundle Name           | API                                                      | Description                                                        |
A
Annie_wang 已提交
79 80 81
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void> | Deletes a **Preferences** instance from the memory and its files from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory.   |
A
annie_wangli 已提交
82 83 84

## How to Develop

A
Annie_wang 已提交
85
1. Import @ohos.data.preferences and related modules to the development environment.
A
annie_wangli 已提交
86

87
   ```js
A
Annie_wang 已提交
88
   import data_preferences from '@ohos.data.preferences';
A
annie_wangli 已提交
89 90
   ```

A
Annie_wang 已提交
91
2. Obtain a **Preferences** instance.
A
annie_wangli 已提交
92

A
Annie_wang 已提交
93
   Read the specified file and load its data to the **Preferences** instance for data operations.
A
Annie_wang 已提交
94

A
Annie_wang 已提交
95 96
   FA model:

97
   ```js
A
Annie_wang 已提交
98 99
   // Obtain the context.
   import featureAbility from '@ohos.ability.featureAbility'
A
Annie_wang 已提交
100 101 102
   let context = featureAbility.getContext();
   
   let preferences = null;
A
Annie_wang 已提交
103
   let promise = data_preferences.getPreferences(context, 'mystore');
A
Annie_wang 已提交
104 105 106 107 108 109
   
   promise.then((pref) => {
       preferences = pref;
   }).catch((err) => {
       console.info("Failed to get the preferences.");
   })
A
Annie_wang 已提交
110 111 112 113 114 115
   ```

   Stage model:

   ```ts
   // Obtain the context.
116
   import UIAbility from '@ohos.app.ability.UIAbility';
A
Annie_wang 已提交
117
   let preferences = null;
A
Annie_wang 已提交
118
   export default class EntryAbility extends UIAbility {
119 120 121 122 123 124 125
       onWindowStageCreate(windowStage) {
           let promise = data_preferences.getPreferences(this.context, 'mystore');
            promise.then((pref) => {
                preferences = pref;
            }).catch((err) => {
                console.info("Failed to get the preferences.");
            })
A
Annie_wang 已提交
126 127
       }
   }
A
Annie_wang 已提交
128 129
   
   
A
annie_wangli 已提交
130 131 132 133
   ```

3. Write data.

A
Annie_wang 已提交
134
   Use **preferences.put()** to write data to the **Preferences** instance.
A
annie_wangli 已提交
135

136
   ```js
A
Annie_wang 已提交
137 138 139
   let putPromise = preferences.put('startup', 'auto');
   putPromise.then(() => {
       console.info("Put the value of 'startup' successfully.");
A
annie_wangli 已提交
140
   }).catch((err) => {
A
Annie_wang 已提交
141
       console.info("Failed to put the value of 'startup'. Cause: " + err);
A
annie_wangli 已提交
142 143
   })
   ```
A
Annie_wang 已提交
144
   
A
annie_wangli 已提交
145 146
4. Read data.

A
Annie_wang 已提交
147
   Use **preferences.get()** to read data.
A
annie_wangli 已提交
148

149
   ```js
A
Annie_wang 已提交
150 151
   let getPromise = preferences.get('startup', 'default');
   getPromise.then((value) => {
A
Annie_wang 已提交
152
       console.info("The value of 'startup' is " + value);
A
annie_wangli 已提交
153
   }).catch((err) => {
A
Annie_wang 已提交
154 155
       console.info("Failed to get the value of 'startup'. Cause: " + err);
   })
A
annie_wangli 已提交
156
   ```
A
Annie_wang 已提交
157
   
A
annie_wangli 已提交
158 159
5. Store data persistently.

A
Annie_wang 已提交
160
   Use **preferences.flush()** to flush data from the **Preferences** instance to its file.
A
annie_wangli 已提交
161

162
   ```js
A
Annie_wang 已提交
163
   preferences.flush();
A
annie_wangli 已提交
164 165
   ```

A
Annie_wang 已提交
166
6. Observe data changes.
A
annie_wangli 已提交
167

A
Annie_wang 已提交
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.
A
annie_wangli 已提交
169

170
   ```js
A
Annie_wang 已提交
171
   let observer = function (key) {
A
Annie_wang 已提交
172 173 174
       console.info("The key" + key + " changed.");
   }
   preferences.on('change', observer);
A
Annie_wang 已提交
175 176
   // The data is changed from 'auto' to 'manual'.
   preferences.put('startup', 'manual', function (err) {
A
Annie_wang 已提交
177 178 179 180
       if (err) {
           console.info("Failed to put the value of 'startup'. Cause: " + err);
           return;
       }
A
Annie_wang 已提交
181
       console.info("Put the value of 'startup' successfully.");
A
Annie_wang 已提交
182 183 184 185 186
       preferences.flush(function (err) {
           if (err) {
               console.info("Failed to flush data. Cause: " + err);
               return;
           }
A
Annie_wang 已提交
187
           console.info("Flushed data successfully."); // The observer will be called.
A
Annie_wang 已提交
188 189
       })
   })
A
annie_wangli 已提交
190 191 192 193
   ```

7. Delete the specified file.

A
Annie_wang 已提交
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.
A
annie_wangli 已提交
195

196
   ```js
A
Annie_wang 已提交
197 198
   let proDelete = data_preferences.deletePreferences(context, 'mystore');
   proDelete.then(() => {
A
Annie_wang 已提交
199
        console.info("Deleted data successfully.");
A
Annie_wang 已提交
200
   }).catch((err) => {
201
        console.info("Failed to delete data. Cause: " + err);
A
Annie_wang 已提交
202
   })
A
annie_wangli 已提交
203
   ```