database-preference-guidelines.md 8.5 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

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

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

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

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

A
Annie_wang 已提交
37 38 39 40 41 42 43 44 45
Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.

**Table 2** APIs for accessing **Preferences** data

| 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.|
| Preferences | getAll(): Promise<Object>                                  | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance.                          |
A
annie_wangli 已提交
46

Z
zengyawen 已提交
47

A
Annie_wang 已提交
48
### Storing Data Persistently
Z
zengyawen 已提交
49

A
annie_wangli 已提交
50
Call the **flush()** method to write the cached data back to its text file for persistent storage.
Z
zengyawen 已提交
51

A
annie_wangli 已提交
52
**Table 4** API for data persistence
Z
zengyawen 已提交
53

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

A
Annie_wang 已提交
58
### Observing Data Changes
Z
zengyawen 已提交
59

A
Annie_wang 已提交
60
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 已提交
61

A
Annie_wang 已提交
62
**Table 5** APIs for observing **Preferences** changes
Z
zengyawen 已提交
63

A
Annie_wang 已提交
64 65
| Class       | API                                                      | Description          |
| ----------- | ------------------------------------------------------------ | -------------- |
A
Annie_wang 已提交
66 67
| 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 已提交
68

A
Annie_wang 已提交
69
### Deleting Data
Z
zengyawen 已提交
70

A
Annie_wang 已提交
71
Use the following APIs to delete a **Preferences** instance or data file.
A
annie_wangli 已提交
72

A
Annie_wang 已提交
73
**Table 6** APIs for deleting **Preferences**
A
annie_wangli 已提交
74

A
Annie_wang 已提交
75 76 77 78
| Package                 | API                                                      | Description                                                        |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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 已提交
79 80 81

## How to Develop

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

84
   ```js
A
Annie_wang 已提交
85
   import data_preferences from '@ohos.data.preferences';
A
annie_wangli 已提交
86 87
   ```

A
Annie_wang 已提交
88
2. Obtain a **Preferences** instance.
A
annie_wangli 已提交
89

A
Annie_wang 已提交
90
   Read the specified file and load its data to the **Preferences** instance for data operations.
A
Annie_wang 已提交
91 92 93
   
   FA model:

94
   ```js
A
Annie_wang 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
   // Obtain the context.
   import featureAbility from '@ohos.ability.featureAbility'
   var context = featureAbility.getContext()

   let promise = data_preferences.getPreferences(context, 'mystore');
   ```

   Stage model:

   ```ts
   // Obtain the context.
   import Ability from '@ohos.application.Ability'
   var context
   class MainAbility extends Ability{
       onWindowStageCreate(windowStage){
           context = this.context
       }
   }

   let promise = data_preferences.getPreferences(context, 'mystore');
A
annie_wangli 已提交
115 116 117 118
   ```

3. Write data.

A
Annie_wang 已提交
119
   Use the **preferences.put()** method to write data to the **Preferences** instance.
A
annie_wangli 已提交
120

121
   ```js
A
Annie_wang 已提交
122
   promise.then((preferences) => {
A
Annie_wang 已提交
123
       let putPromise = preferences.put('startup', 'auto');
A
Annie_wang 已提交
124
       putPromise.then(() => {
A
Annie_wang 已提交
125
           console.info("Put the value of 'startup' successfully.");
A
annie_wangli 已提交
126
       }).catch((err) => {
A
Annie_wang 已提交
127
           console.info("Failed to put the value of 'startup'. Cause: " + err);
A
annie_wangli 已提交
128 129
       })
   }).catch((err) => {
A
Annie_wang 已提交
130
       console.info("Failed to get the preferences.");
A
annie_wangli 已提交
131 132 133 134 135
   })
   ```

4. Read data.

A
Annie_wang 已提交
136
   Use the **preferences.get()** method to read data.
A
annie_wangli 已提交
137

138
   ```js
A
Annie_wang 已提交
139
   promise.then((preferences) => {
A
Annie_wang 已提交
140 141 142 143 144 145
     let getPromise = preferences.get('startup', 'default');
     getPromise.then((value) => {
       console.info("The value of 'startup' is " + value);
     }).catch((err) => {
       console.info("Failed to get the value of 'startup'. Cause: " + err);
     })
A
annie_wangli 已提交
146
   }).catch((err) => {
A
Annie_wang 已提交
147 148
       console.info("Failed to get the preferences.")
   });
A
annie_wangli 已提交
149 150 151 152
   ```

5. Store data persistently.

A
Annie_wang 已提交
153
   Use the **flush()** method to flush data from the **Preferences** instance to its file.
A
annie_wangli 已提交
154

155
   ```js
A
Annie_wang 已提交
156
   preferences.flush();
A
annie_wangli 已提交
157 158
   ```

A
Annie_wang 已提交
159
6. Observe data changes.
A
annie_wangli 已提交
160

A
Annie_wang 已提交
161
   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 已提交
162

163
   ```js
A
Annie_wang 已提交
164 165 166 167 168 169 170 171 172
   var observer = function (key) {
       console.info("The key" + key + " changed.");
   }
   preferences.on('change', observer);
   preferences.put('startup', 'auto', function (err) {
       if (err) {
           console.info("Failed to put the value of 'startup'. Cause: " + err);
           return;
       }
A
Annie_wang 已提交
173
        console.info("Put the value of 'startup' successfully.");
A
Annie_wang 已提交
174 175 176 177 178
       preferences.flush(function (err) {
           if (err) {
               console.info("Failed to flush data. Cause: " + err);
               return;
           }
A
Annie_wang 已提交
179
            console.info("Flushed data successfully."); // The observer will be called.
A
Annie_wang 已提交
180 181
       })
   })
A
annie_wangli 已提交
182 183 184 185
   ```

7. Delete the specified file.

A
Annie_wang 已提交
186
   Use the **deletePreferences** method 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 已提交
187

188
   ```js
A
Annie_wang 已提交
189 190
   let proDelete = data_preferences.deletePreferences(context, 'mystore');
   proDelete.then(() => {
A
Annie_wang 已提交
191
        console.info("Deleted data successfully.");
A
Annie_wang 已提交
192
   }).catch((err) => {
A
Annie_wang 已提交
193
        console.info("Failed to delete data. Cause: " + err);
A
Annie_wang 已提交
194
   })
A
annie_wangli 已提交
195
   ```