1# Persisting Preferences Data
2
3
4## When to Use
5
6The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs, including querying, modifying, and persisting KV pairs. You can use **Preferences** when you want a unique storage for global data. 
7
8The **Preferences** data is cached in the memory, which allows fast access when the data is required. If you want to persist data, you can use **flush()** to save the data to a file. The **Preferences** data occupies the application's memory space and cannot be encrypted through configuration. Therefore, it is recommended for storing personalized settings (font size and whether to enable the night mode) of applications. 
9
10
11## Working Principles
12
13User applications call **Preference** through the ArkTS interface to read and write data files. You can load the data of a **Preferences** persistence file to a **Preferences** instance. Each file uniquely corresponds to an instance. The system stores the instance in memory through a static container until the instance is removed from the memory or the file is deleted. The following figure illustrates how **Preference** works.
14
15The preference persistent file of an application is stored in the application sandbox. You can use **context** to obtain the file path. For details, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths).
16
17**Figure 1** Preferences working mechanism 
18
19![preferences](figures/preferences.jpg)
20
21
22## Constraints
23
24- Preferences are not thread-safe and may cause file damage and data loss when used in multi-process scenarios. Do not use preferences in multi-process scenarios.
25
26- The key in a KV pair must be a string and cannot be empty or exceed 1024 bytes.
27
28- If the value is of the string type, use the UTF-8 encoding format. It can be empty or a string not longer than 16 x 1024 x 1024 bytes.
29
30- The memory usage increases with the amount of **Preferences** data. The maximum number of data records recommended is 10,000. Otherwise, high memory overheads will be caused.
31
32
33## Available APIs
34
35The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis-arkdata/js-apis-data-preferences.md).
36
37| API                                                    | Description                                                        |
38| ------------------------------------------------------------ | ------------------------------------------------------------ |
39| getPreferencesSync(context: Context, options: Options): Preferences | Obtains a **Preferences** instance. This API returns the result synchronously.<br/> An asynchronous API is also provided.                   |
40| putSync(key: string, value: ValueType): void                 | Writes data to the **Preferences** instance. This API returns the result synchronously. An asynchronous API is also provided.<br/>You can use **flush()** to persist the **Preferences** instance data.|
41| hasSync(key: string): boolean                                   | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. This API returns the result synchronously.<br/> An asynchronous API is also provided.|
42| getSync(key: string, defValue: ValueType): ValueType              | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. This API returns the result synchronously.<br/> An asynchronous API is also provided.|
43| deleteSync(key: string): void                                | Deletes a KV pair from the **Preferences** instance. This API returns the result synchronously.<br/> An asynchronous API is also provided.|
44| flush(callback: AsyncCallback&lt;void&gt;): void             | Flushes the data of this **Preferences** instance to a file for data persistence.|
45| on(type: 'change', callback: Callback&lt;string&gt;): void | Subscribes to data changes. A callback will be invoked after **flush()** is executed for the data changed.|
46| off(type: 'change', callback?: Callback&lt;string&gt;): void | Unsubscribes from data changes.                                          |
47| deletePreferences(context: Context, options: Options, callback: AsyncCallback&lt;void&gt;): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.|
48
49
50## How to Develop
51
521. Import the **@kit.ArkData** module.
53   
54   ```ts
55   import { preferences } from '@kit.ArkData';
56   ```
57
582. Obtain a **Preferences** instance.
59
60   Stage model:
61
62
63   ```ts
64   import { UIAbility } from '@kit.AbilityKit';
65   import { BusinessError } from '@kit.BasicServicesKit';
66   import { window } from '@kit.ArkUI';
67
68   let dataPreferences: preferences.Preferences | null = null;
69
70   class EntryAbility extends UIAbility {
71     onWindowStageCreate(windowStage: window.WindowStage) {
72       let options: preferences.Options = { name: 'myStore' };
73       dataPreferences = preferences.getPreferencesSync(this.context, options);
74     }
75   }
76   ```
77
78   FA model:
79
80
81   ```ts
82   // Obtain the context.
83   import { featureAbility } from '@kit.AbilityKit';
84   import { BusinessError } from '@kit.BasicServicesKit';
85   
86   let context = featureAbility.getContext();
87   let options: preferences.Options =  { name: 'myStore' };
88   let dataPreferences: preferences.Preferences = preferences.getPreferencesSync(context, options);
89   ```
90
913. Write data.
92
93   Use **putSync()** to save data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary.
94
95   > **NOTE**
96   >
97   > If the key already exists, **putSync()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
98
99   Example:
100
101   ```ts
102   import { util } from '@kit.ArkTS';
103   if (dataPreferences.hasSync('startup')) {
104     console.info("The key 'startup' is contained.");
105   } else {
106     console.info("The key 'startup' does not contain.");
107     // Add a KV pair.
108     dataPreferences.putSync('startup', 'auto');
109     // If the string contains special characters, convert the string into a Uint8Array before storing it.
110     let uInt8Array1 = new util.TextEncoder().encodeInto("~! @#¥%......&* () --+? ");
111     dataPreferences.putSync('uInt8', uInt8Array1);
112   }
113   ```
114
1154. Read data.
116
117   Use **getSync()** to obtain the value of the specified key. If the value is null or is not of the default value type, the default data is returned.
118
119   Example:
120
121   ```ts
122   let val = dataPreferences.getSync('startup', 'default');
123   console.info("The 'startup' value is " + val);
124   // If the value is a string containing special characters, it is stored in the Uint8Array format. Convert the obtained Uint8Array into a string.
125   let uInt8Array2 : preferences.ValueType = dataPreferences.getSync('uInt8', new Uint8Array(0));
126   let textDecoder = util.TextDecoder.create('utf-8');
127   val = textDecoder.decodeWithStream(uInt8Array2 as Uint8Array);
128   console.info("The 'uInt8' value is " + val);
129   ```
130
1315. Delete data.
132
133   Use **deleteSync()** to delete a KV pair.<br>Example:
134
135
136   ```ts
137   dataPreferences.deleteSync('startup');
138   ```
139
1406. Persist data.
141
142   You can use **flush()** to persist the data held in a **Preferences** instance to a file.<br>Example:
143
144   ```ts
145   dataPreferences.flush((err: BusinessError) => {
146     if (err) {
147       console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
148       return;
149     }
150     console.info('Succeeded in flushing.');
151   })
152   ```
153
1547. Subscribe to data changes.
155
156   Specify an observer as the callback to return the 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.<br>Example:
157
158   ```ts
159   let observer = (key: string) => {
160     console.info('The key' + key + 'changed.');
161   }
162   dataPreferences.on('change', observer);
163   // The data is changed from 'auto' to 'manual'.
164   dataPreferences.put('startup', 'manual', (err: BusinessError) => {
165     if (err) {
166       console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
167       return;
168     }
169     console.info("Succeeded in putting the value of 'startup'.");
170     if (dataPreferences !== null) {
171       dataPreferences.flush((err: BusinessError) => {
172         if (err) {
173           console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
174           return;
175         }
176         console.info('Succeeded in flushing.');
177       })
178     }
179   })
180   ```
181
1828. Delete a **Preferences** instance from the memory.
183
184   Use **deletePreferences()** to delete a **Preferences** instance from the memory. If the **Preferences** instance has a persistent file, the persistent file and its backup and corrupted files will also be deleted.
185
186   > **NOTE**
187   >
188   > - The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
189   > 
190   > - The deleted data and files cannot be restored.
191
192   Example:
193
194
195   ```ts
196   preferences.deletePreferences(this.context, options, (err: BusinessError) => {
197     if (err) {
198       console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
199         return;
200     }
201     console.info('Succeeded in deleting preferences.');
202   })
203   ```