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

A
annie_wangli 已提交
3
## When to Use
Z
zengyawen 已提交
4

A
Annie_wang 已提交
5
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 已提交
6

A
annie_wangli 已提交
7
## Available APIs
Z
zengyawen 已提交
8

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

A
Annie_wang 已提交
11
### Creating a Preferences Instance
Z
zengyawen 已提交
12

A
Annie_wang 已提交
13
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 已提交
14

A
Annie_wang 已提交
15
**Table 1** API for creating a **Preferences** instance
A
annie_wangli 已提交
16 17 18

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

A
Annie_wang 已提交
21
### Writing Data
Z
zengyawen 已提交
22

A
Annie_wang 已提交
23
Call the **put()** method to add or modify data in a **Preferences** instance.
A
annie_wangli 已提交
24 25 26 27 28

**Table 2** API for writing data

| Class   | API                                            | Description                                           |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
A
Annie_wang 已提交
29
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.|
Z
zengyawen 已提交
30

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

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

**Table 3** API for reading data

| Class   | API                                                    | Description                                           |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
A
Annie_wang 已提交
39
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.|
Z
zengyawen 已提交
40

A
Annie_wang 已提交
41
### Storing Data Persistently
Z
zengyawen 已提交
42

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

A
annie_wangli 已提交
45
**Table 4** API for data persistence
Z
zengyawen 已提交
46

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

A
Annie_wang 已提交
51
### Observing Data Changes
Z
zengyawen 已提交
52

A
Annie_wang 已提交
53
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 已提交
54

A
Annie_wang 已提交
55
**Table 5** APIs for observing **Preferences** changes
Z
zengyawen 已提交
56

A
annie_wangli 已提交
57 58
| Class   | API                                                      | Description          |
| ------- | ------------------------------------------------------------ | -------------- |
A
Annie_wang 已提交
59 60
| 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 已提交
61

A
Annie_wang 已提交
62
### Deleting Data
Z
zengyawen 已提交
63

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

A
Annie_wang 已提交
66
**Table 6** APIs for deleting **Preferences**
A
annie_wangli 已提交
67 68 69

| Package             | API                                              | Description                                                        |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
70 71
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise<void>;     | Deletes a **Preferences** instance from the cache and deletes its file 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 已提交
72 73 74

## How to Develop

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

77
   ```js
A
Annie_wang 已提交
78
   import data_preferences from '@ohos.data.preferences'
A
annie_wangli 已提交
79 80
   ```

A
Annie_wang 已提交
81
2. Create a **Preferences** instance.
A
annie_wangli 已提交
82

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

3. Write data.

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

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

4. Read data.

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

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

5. Store data persistently.

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

125
   ```js
A
Annie_wang 已提交
126
   preferences.flush();
A
annie_wangli 已提交
127 128
   ```

A
Annie_wang 已提交
129
6. Observe data changes.
A
annie_wangli 已提交
130

A
Annie_wang 已提交
131
   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 已提交
132

133
   ```js
A
Annie_wang 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    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 已提交
152 153 154 155
   ```

7. Delete the specified file.

A
Annie_wang 已提交
156
   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 已提交
157

158
   ```js
A
Annie_wang 已提交
159 160 161 162 163 164
    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 已提交
165
   ```