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

A
Annie_wang 已提交
3 4 5 6
> **NOTE**
>
> 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_wangli 已提交
7
## When to Use
Z
zengyawen 已提交
8

A
Annie_wang 已提交
9
Preferences are ideal for storing data frequently used by applications, 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.
Z
zengyawen 已提交
10

A
annie_wangli 已提交
11
## Available APIs
Z
zengyawen 已提交
12

A
Annie_wang 已提交
13
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md).
Z
zengyawen 已提交
14

A
Annie_wang 已提交
15
### Creating a Preferences Instance
Z
zengyawen 已提交
16

A
Annie_wang 已提交
17
Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance.
A
annie_wangli 已提交
18

A
Annie_wang 已提交
19
**Table 1** API for creating a **Preferences** instance
A
annie_wangli 已提交
20 21 22

| Package             | API                                     | Description                                       |
| ----------------- | ------------------------------------------- | ------------------------------------------- |
A
Annie_wang 已提交
23
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
Z
zengyawen 已提交
24

A
Annie_wang 已提交
25
### Writing Data
Z
zengyawen 已提交
26

A
Annie_wang 已提交
27
Call the **put()** method to add or modify data in a **Preferences** instance.
A
annie_wangli 已提交
28 29 30 31 32

**Table 2** API for writing data

| Class   | API                                            | Description                                           |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
A
Annie_wang 已提交
33
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
Z
zengyawen 已提交
34

A
Annie_wang 已提交
35
### Reading Data
Z
zengyawen 已提交
36

A
Annie_wang 已提交
37
Call the **get()** method to read data from a **Preferences** instance.
A
annie_wangli 已提交
38 39 40 41 42

**Table 3** API for reading data

| Class   | API                                                    | Description                                           |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
A
Annie_wang 已提交
43
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
Z
zengyawen 已提交
44

A
Annie_wang 已提交
45
### Storing Data Persistently
Z
zengyawen 已提交
46

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

A
annie_wangli 已提交
49
**Table 4** API for data persistence
Z
zengyawen 已提交
50

A
annie_wangli 已提交
51 52
| Class   | API                 | Description                                   |
| ------- | ----------------------- | --------------------------------------- |
A
Annie_wang 已提交
53
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.|
Z
zengyawen 已提交
54

A
Annie_wang 已提交
55
### Observing Data Changes
Z
zengyawen 已提交
56

A
Annie_wang 已提交
57
You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data.
Z
zengyawen 已提交
58

A
Annie_wang 已提交
59
**Table 5** APIs for observing **Preferences** changes
Z
zengyawen 已提交
60

A
annie_wangli 已提交
61 62
| Class   | API                                                      | Description          |
| ------- | ------------------------------------------------------------ | -------------- |
A
Annie_wang 已提交
63 64
| 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 已提交
65

A
Annie_wang 已提交
66
### Deleting Data
Z
zengyawen 已提交
67

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

A
Annie_wang 已提交
70
**Table 6** APIs for deleting **Preferences**
A
annie_wangli 已提交
71 72 73

| Package             | API                                              | Description                                                        |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
74
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>;     | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
A
Annie_wang 已提交
75
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
A
annie_wangli 已提交
76 77 78

## How to Develop

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

81
   ```js
A
Annie_wang 已提交
82
   import data_preferences from '@ohos.data.preferences'
A
annie_wangli 已提交
83 84
   ```

A
Annie_wang 已提交
85
2. Create a **Preferences** instance.
A
annie_wangli 已提交
86

A
Annie_wang 已提交
87
   Read the specified file and load its data to the **Preferences** instance for data operations.
88
   ```js
A
Annie_wang 已提交
89
   let promise = data_preferences.getPreferences(this.context, 'mystore')
A
annie_wangli 已提交
90 91 92 93
   ```

3. Write data.

A
Annie_wang 已提交
94
   Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance.
A
annie_wangli 已提交
95

96
   ```js
A
Annie_wang 已提交
97
   promise.then((preferences) => {
A
Annie_wang 已提交
98 99
       let putPromise = preferences.put('startup', 'auto')
       putPromise.then(() => {
A
annie_wangli 已提交
100 101
           console.info("Put the value of startup successfully.")
       }).catch((err) => {
A
Annie_wang 已提交
102
           console.info("Failed to put the value of startup with err: " + err)
A
annie_wangli 已提交
103 104
       })
   }).catch((err) => {
A
Annie_wang 已提交
105
       console.info("Failed to get the preferences")
A
annie_wangli 已提交
106 107 108 109 110
   })
   ```

4. Read data.

A
Annie_wang 已提交
111
   Use the **get()** method of the **Preferences** class to read data.
A
annie_wangli 已提交
112

113
   ```js
A
Annie_wang 已提交
114 115
   promise.then((preferences) => {
       let getPromise = preferences.get('startup', 'default')
A
annie_wangli 已提交
116 117 118
       getPromise.then((value) => {
           console.info("The value of startup is " + value)
       }).catch((err) => {
A
Annie_wang 已提交
119
           console.info("Failed to get the value of startup with err: " + err)
A
annie_wangli 已提交
120 121
       })
   }).catch((err) => {
A
Annie_wang 已提交
122
       console.info("Failed to get the preferences")})
A
annie_wangli 已提交
123 124 125 126
   ```

5. Store data persistently.

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

129
   ```js
A
Annie_wang 已提交
130
   preferences.flush();
A
annie_wangli 已提交
131 132
   ```

A
Annie_wang 已提交
133
6. Observe data changes.
A
annie_wangli 已提交
134

A
Annie_wang 已提交
135
   Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change.
A
annie_wangli 已提交
136

137
   ```js
A
Annie_wang 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    var observer = function (key) {
        console.info("The key of " + key + " changed.")
    }
    preferences.on('change', observer)
    preferences.put('startup', 'auto', function (err) {
        if (err) {
            console.info("Failed to put the value of startup with err: " + err)
            return
        }
        console.info("Put the value of startup successfully.")
        preferences.flush(function (err) {
            if (err) {
                console.info("Failed to flush data to file with err: " + err)
                return
            }
            console.info("Flushed to file successfully.")    // Observer will be called.
        })
    })
A
annie_wangli 已提交
156 157 158 159
   ```

7. Delete the specified file.

A
Annie_wang 已提交
160
   Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted 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.
A
annie_wangli 已提交
161

162
   ```js
A
Annie_wang 已提交
163 164 165 166 167 168
    let proDelete = data_preferences.deletePreferences(context, 'mystore')
    proDelete.then(() => {
        console.info("Data deleted successfully.")
    }).catch((err) => {
        console.info("Failed to delete data with err: " + err)
    })
A
annie_wangli 已提交
169
   ```