1# @ohos.data.preferences (User Preferences)
2
3The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs, including querying, modifying, and persisting KV pairs.
4
5The 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.
6
7The default encryption level of user preferences is EL2, and the persistent files are stored in the corresponding **el2/** directory. If there is no lock screen password, the sendable preferences can be directly accessed after the device is powered on. If there is a lock screen password, the data can be accessed only after at least one successful unlock operation (by PIN, fingerprint, or facial authentication). Avoid direct access to preferences data without the screen unlock operation. For details about how to modify the encryption level, see [Obtaining and Modifying Encryption Levels](../../../application-dev/application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels).
8
9> **NOTE**
10>
11> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
12>
13> - 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.
14
15## Modules to Import
16
17```ts
18import { preferences } from '@kit.ArkData';
19```
20
21## Constants
22
23**Atomic service API**: This API can be used in atomic services since API version 11.
24
25**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
26
27| Name            | Type| Readable| Writable| Description                                   |
28| ---------------- | -------- | ---- | ---- | --------------------------------------- |
29| MAX_KEY_LENGTH   | number   | Yes  | No  | Maximum length of a key, which is 1024 bytes.    |
30| MAX_VALUE_LENGTH | number   | Yes  | No  | Maximum value length, which is 16 x 1024 x 1024 bytes.|
31
32
33## preferences.getPreferences
34
35getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void
36
37Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result.
38
39**Atomic service API**: This API can be used in atomic services since API version 11.
40
41**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
42
43**Parameters**
44
45| Name  | Type                                            | Mandatory| Description                                                        |
46| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
47| context  | Context            | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).                                                |
48| name     | string                                           | Yes  | Name of the **Preferences** instance.                                     |
49| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object.|
50
51**Error codes**
52
53For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
54
55| ID| Error Message                       |
56| -------- | ------------------------------ |
57| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
58| 15500000 | Inner error.                   |
59
60**Example**
61
62FA model:
63
64<!--code_no_check_fa-->
65```ts
66import { featureAbility } from '@kit.AbilityKit';
67import { BusinessError } from '@kit.BasicServicesKit';
68
69let context = featureAbility.getContext();
70let dataPreferences: preferences.Preferences | null = null;
71
72preferences.getPreferences(context, 'myStore', (err: BusinessError, val: preferences.Preferences) => {
73  if (err) {
74    console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
75    return;
76  }
77  dataPreferences = val;
78  console.info("Succeeded in getting preferences.");
79})
80```
81
82Stage model:
83
84```ts
85import { UIAbility } from '@kit.AbilityKit';
86import { BusinessError } from '@kit.BasicServicesKit';
87import { window } from '@kit.ArkUI';
88
89let dataPreferences: preferences.Preferences | null = null;
90
91class EntryAbility extends UIAbility {
92  onWindowStageCreate(windowStage: window.WindowStage) {
93    preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: preferences.Preferences) => {
94      if (err) {
95        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
96        return;
97      }
98      dataPreferences = val;
99      console.info("Succeeded in getting preferences.");
100    })
101  }
102}
103```
104
105## preferences.getPreferences
106
107getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
108
109Obtains a **Preferences** instance. This API uses a promise to return the result.
110
111**Atomic service API**: This API can be used in atomic services since API version 11.
112
113**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
114
115**Parameters**
116
117| Name | Type                                 | Mandatory| Description                   |
118| ------- | ------------------------------------- | ---- | ----------------------- |
119| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).           |
120| name    | string                                | Yes  | Name of the **Preferences** instance.|
121
122**Return value**
123
124| Type                                      | Description                              |
125| ------------------------------------------ | ---------------------------------- |
126| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.|
127
128**Error codes**
129
130For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
131
132| ID| Error Message                       |
133| -------- | ------------------------------ |
134| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
135| 15500000 | Inner error.                   |
136
137**Example**
138
139FA model:
140
141<!--code_no_check_fa-->
142```ts
143// Obtain the context.
144import { featureAbility } from '@kit.AbilityKit';
145import { BusinessError } from '@kit.BasicServicesKit';
146
147let context = featureAbility.getContext();
148
149let dataPreferences: preferences.Preferences | null = null;
150let promise = preferences.getPreferences(context, 'myStore');
151promise.then((object: preferences.Preferences) => {
152  dataPreferences = object;
153  console.info("Succeeded in getting preferences.");
154}).catch((err: BusinessError) => {
155  console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
156})
157```
158
159Stage model:
160
161```ts
162import { UIAbility } from '@kit.AbilityKit';
163import { BusinessError } from '@kit.BasicServicesKit';
164import { window } from '@kit.ArkUI';
165
166let dataPreferences: preferences.Preferences | null = null;
167
168class EntryAbility extends UIAbility {
169  onWindowStageCreate(windowStage: window.WindowStage) {
170    let promise = preferences.getPreferences(this.context, 'myStore');
171    promise.then((object: preferences.Preferences) => {
172      dataPreferences = object;
173      console.info("Succeeded in getting preferences.");
174    }).catch((err: BusinessError) => {
175      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
176    })
177  }
178}
179```
180
181## preferences.getPreferences<sup>10+</sup>
182
183getPreferences(context: Context, options: Options, callback: AsyncCallback&lt;Preferences&gt;): void
184
185Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result.
186
187**Atomic service API**: This API can be used in atomic services since API version 11.
188
189**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
190
191**Parameters**
192
193| Name  | Type                                         | Mandatory| Description                                                                                                                                                                          |
194| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
195| context  | Context                                       | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
196| options  | [Options](#options10)                              | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
197| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object.                                                                                   |
198
199**Error codes**
200
201For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
202
203| ID| Error Message                       |
204| -------- | ------------------------------ |
205| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
206| 801      | Capability not supported.     |
207| 15500000 | Inner error.                  |
208| 15501001 | Only supported in stage mode. |
209| 15501002 | The data group id is not valid.     |
210
211**Example**
212
213FA model:
214
215<!--code_no_check_fa-->
216```ts
217// Obtain the context.
218import { featureAbility } from '@kit.AbilityKit';
219import { BusinessError } from '@kit.BasicServicesKit';
220
221let context = featureAbility.getContext();
222let dataPreferences: preferences.Preferences | null = null;
223
224let options: preferences.Options = { name: 'myStore' };
225preferences.getPreferences(context, options, (err: BusinessError, val: preferences.Preferences) => {
226  if (err) {
227    console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
228    return;
229  }
230  dataPreferences = val;
231  console.info("Succeeded in getting preferences.");
232})
233```
234
235
236Stage model:
237
238```ts
239import { UIAbility } from '@kit.AbilityKit';
240import { BusinessError } from '@kit.BasicServicesKit';
241import { window } from '@kit.ArkUI';
242
243let dataPreferences: preferences.Preferences | null = null;
244
245class EntryAbility extends UIAbility {
246  onWindowStageCreate(windowStage: window.WindowStage) {
247    let options: preferences.Options = { name: 'myStore' };
248    preferences.getPreferences(this.context, options, (err: BusinessError, val: preferences.Preferences) => {
249      if (err) {
250        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
251        return;
252      }
253      dataPreferences = val;
254      console.info("Succeeded in getting preferences.");
255    })
256  }
257}
258```
259
260## preferences.getPreferences<sup>10+</sup>
261
262getPreferences(context: Context, options: Options): Promise&lt;Preferences&gt;
263
264Obtains a **Preferences** instance. This API uses a promise to return the result.
265
266**Atomic service API**: This API can be used in atomic services since API version 11.
267
268**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
269
270**Parameters**
271
272| Name | Type            | Mandatory| Description                                                                                                                                                                          |
273| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
274| context | Context          | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
275| options | [Options](#options10) | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
276
277**Return value**
278
279| Type                                   | Description                              |
280| --------------------------------------- | ---------------------------------- |
281| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.|
282
283**Error codes**
284
285For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
286
287| ID| Error Message                       |
288| -------- | ------------------------------ |
289| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
290| 801      | Capability not supported.     |
291| 15500000 | Inner error.                   |
292| 15501001 | Only supported in stage mode. |
293| 15501002 | The data group id is not valid.     |
294
295**Example**
296
297FA model:
298
299<!--code_no_check_fa-->
300```ts
301// Obtain the context.
302import { featureAbility } from '@kit.AbilityKit';
303import { BusinessError } from '@kit.BasicServicesKit';
304
305let context = featureAbility.getContext();
306
307let dataPreferences: preferences.Preferences | null = null;
308let options: preferences.Options = { name: 'myStore' };
309let promise = preferences.getPreferences(context, options);
310promise.then((object: preferences.Preferences) => {
311  dataPreferences = object;
312  console.info("Succeeded in getting preferences.");
313}).catch((err: BusinessError) => {
314  console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
315})
316```
317
318Stage model:
319
320```ts
321import { UIAbility } from '@kit.AbilityKit';
322import { BusinessError } from '@kit.BasicServicesKit';
323import { window } from '@kit.ArkUI';
324
325let dataPreferences: preferences.Preferences | null = null;
326
327class EntryAbility extends UIAbility {
328  onWindowStageCreate(windowStage: window.WindowStage) {
329    let options: preferences.Options = { name: 'myStore' };
330    let promise = preferences.getPreferences(this.context, options);
331    promise.then((object: preferences.Preferences) => {
332      dataPreferences = object;
333      console.info("Succeeded in getting preferences.");
334    }).catch((err: BusinessError) => {
335      console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
336    })
337  }
338}
339```
340
341## preferences.getPreferencesSync<sup>10+</sup>
342
343getPreferencesSync(context: Context, options: Options): Preferences
344
345Obtains a **Preferences** instance. This API returns the result synchronously.
346
347**Atomic service API**: This API can be used in atomic services since API version 11.
348
349**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
350
351**Parameters**
352
353| Name | Type                 | Mandatory| Description                                                        |
354| ------- | --------------------- | ---- | ------------------------------------------------------------ |
355| context | Context               | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
356| options | [Options](#options10) | Yes  | Configuration options of the **Preferences** instance.                           |
357
358**Return value**
359
360| Type                       | Description                 |
361| --------------------------- | --------------------- |
362| [Preferences](#preferences) | **Preferences** instance obtained.|
363
364**Error codes**
365
366For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
367
368| ID| Error Message                       |
369| -------- | ------------------------------ |
370| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
371| 801      | Capability not supported.     |
372| 15500000 | Inner error.                   |
373| 15501001 | Only supported in stage mode.   |
374| 15501002 | The data group id is not valid. |
375
376**Example**
377
378FA model:
379
380<!--code_no_check_fa-->
381```ts
382// Obtain the context.
383import { featureAbility } from '@kit.AbilityKit';
384
385let context = featureAbility.getContext();
386let dataPreferences: preferences.Preferences | null = null;
387
388let options: preferences.Options = { name: 'myStore' };
389dataPreferences = preferences.getPreferencesSync(context, options);
390```
391
392Stage model:
393
394```ts
395import { UIAbility } from '@kit.AbilityKit';
396import { window } from '@kit.ArkUI';
397
398let dataPreferences: preferences.Preferences | null = null;
399
400class EntryAbility extends UIAbility {
401  onWindowStageCreate(windowStage: window.WindowStage) {
402    let options: preferences.Options = { name: 'myStore' };
403    dataPreferences = preferences.getPreferencesSync(this.context, options);
404  }
405}
406```
407
408## preferences.deletePreferences
409
410deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
411
412Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.
413
414Avoid using a deleted **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the deleted **Preferences** instance to null. The system will reclaim them in a unified manner.
415
416This API cannot be called concurrently with other **preferences** APIs.
417
418**Atomic service API**: This API can be used in atomic services since API version 11.
419
420**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
421
422**Parameters**
423
424| Name  | Type                                 | Mandatory| Description                                                |
425| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
426| context  | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).                                        |
427| name     | string                                | Yes  | Name of the **Preferences** instance.                             |
428| callback | AsyncCallback&lt;void&gt;             | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
429
430**Error codes**
431
432For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
433
434| ID| Error Message                       |
435| -------- | ------------------------------ |
436| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
437| 15500000 | Inner error.                   |
438| 15500010 | Failed to delete preferences file. |
439
440**Example**
441
442FA model:
443
444<!--code_no_check_fa-->
445```ts
446// Obtain the context.
447import { featureAbility } from '@kit.AbilityKit';
448import { BusinessError } from '@kit.BasicServicesKit';
449
450let context = featureAbility.getContext();
451
452preferences.deletePreferences(context, 'myStore', (err: BusinessError) => {
453  if (err) {
454    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
455    return;
456  }
457  console.info("Succeeded in deleting preferences.");
458})
459```
460
461Stage model:
462
463```ts
464import { UIAbility } from '@kit.AbilityKit';
465import { BusinessError } from '@kit.BasicServicesKit';
466import { window } from '@kit.ArkUI';
467
468class EntryAbility extends UIAbility {
469  onWindowStageCreate(windowStage: window.WindowStage) {
470    preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
471      if (err) {
472        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
473        return;
474      }
475      console.info("Succeeded in deleting preferences.");
476    })
477  }
478}
479```
480
481## preferences.deletePreferences
482
483deletePreferences(context: Context, name: string): Promise&lt;void&gt;
484
485Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.
486
487Avoid using a deleted **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the deleted **Preferences** instance to null. The system will reclaim them in a unified manner.
488
489This API cannot be called concurrently with other **preferences** APIs.
490
491**Atomic service API**: This API can be used in atomic services since API version 11.
492
493**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
494
495**Parameters**
496
497| Name | Type                                 | Mandatory| Description                   |
498| ------- | ------------------------------------- | ---- | ----------------------- |
499| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).           |
500| name    | string                                | Yes  | Name of the **Preferences** instance.|
501
502**Return value**
503
504| Type               | Description                     |
505| ------------------- | ------------------------- |
506| Promise&lt;void&gt; | Promise that returns no value.|
507
508**Error codes**
509
510For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
511
512| ID| Error Message                       |
513| -------- | ------------------------------ |
514| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
515| 15500000 | Inner error.                   |
516| 15500010 | Failed to delete preferences file. |
517
518**Example**
519
520FA model:
521
522<!--code_no_check_fa-->
523```ts
524// Obtain the context.
525import { featureAbility } from '@kit.AbilityKit';
526import { BusinessError } from '@kit.BasicServicesKit';
527
528let context = featureAbility.getContext();
529
530let promise = preferences.deletePreferences(context, 'myStore');
531promise.then(() => {
532  console.info("Succeeded in deleting preferences.");
533}).catch((err: BusinessError) => {
534  console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
535})
536```
537
538Stage model:
539
540```ts
541import { UIAbility } from '@kit.AbilityKit';
542import { BusinessError } from '@kit.BasicServicesKit';
543import { window } from '@kit.ArkUI';
544
545class EntryAbility extends UIAbility {
546  onWindowStageCreate(windowStage: window.WindowStage) {
547    let promise = preferences.deletePreferences(this.context, 'myStore');
548    promise.then(() => {
549      console.info("Succeeded in deleting preferences.");
550    }).catch((err: BusinessError) => {
551      console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
552    })
553  }
554}
555```
556
557## preferences.deletePreferences<sup>10+</sup>
558
559deletePreferences(context: Context, options: Options, callback: AsyncCallback&lt;void&gt;): void
560
561Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.
562
563Avoid using a deleted **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the deleted **Preferences** instance to null. The system will reclaim them in a unified manner.
564
565This API cannot be called concurrently with other **preferences** APIs.
566
567**Atomic service API**: This API can be used in atomic services since API version 11.
568
569**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
570
571**Parameters**
572
573| Name  | Type                     | Mandatory| Description                                                                                                                                                                          |
574| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
575| context  | Context                   | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
576| options  | [Options](#options10)          | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
577| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.                                                                                                                          |
578
579**Error codes**
580
581For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
582
583| ID| Error Message                       |
584| -------- | ------------------------------ |
585| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
586| 801      | Capability not supported.     |
587| 15500000 | Inner error.                   |
588| 15500010 | Failed to delete preferences file. |
589| 15501001 | Only supported in stage mode. |
590| 15501002 | The data group id is not valid. |
591
592**Example**
593
594FA model:
595
596<!--code_no_check_fa-->
597```ts
598// Obtain the context.
599import { featureAbility } from '@kit.AbilityKit';
600import { BusinessError } from '@kit.BasicServicesKit';
601
602let context = featureAbility.getContext();
603
604let options: preferences.Options = { name: 'myStore' };
605preferences.deletePreferences(context, options, (err: BusinessError) => {
606  if (err) {
607    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
608    return;
609  }
610  console.info("Succeeded in deleting preferences.");
611})
612```
613
614Stage model:
615
616```ts
617import { UIAbility } from '@kit.AbilityKit';
618import { BusinessError } from '@kit.BasicServicesKit';
619import { window } from '@kit.ArkUI';
620
621class EntryAbility extends UIAbility {
622  onWindowStageCreate(windowStage: window.WindowStage) {
623    let options: preferences.Options = { name: 'myStore' };
624    preferences.deletePreferences(this.context, options, (err: BusinessError) => {
625      if (err) {
626        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
627        return;
628      }
629      console.info("Succeeded in deleting preferences.");
630    })
631  }
632}
633```
634
635
636## preferences.deletePreferences<sup>10+</sup>
637
638deletePreferences(context: Context, options: Options): Promise&lt;void&gt;
639
640Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.
641
642Avoid using a deleted **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the deleted **Preferences** instance to null. The system will reclaim them in a unified manner.
643
644This API cannot be called concurrently with other **preferences** APIs.
645
646**Atomic service API**: This API can be used in atomic services since API version 11.
647
648**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
649
650**Parameters**
651
652| Name | Type            | Mandatory| Description                                                                                                                                                                          |
653| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
654| context | Context          | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
655| options | [Options](#options10) | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
656
657**Return value**
658
659| Type               | Description                     |
660| ------------------- | ------------------------- |
661| Promise&lt;void&gt; | Promise that returns no value.|
662
663**Error codes**
664
665For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
666
667| ID| Error Message                       |
668| -------- | ------------------------------ |
669| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
670| 801      | Capability not supported.     |
671| 15500000 | Inner error.                   |
672| 15500010 | Failed to delete preferences file. |
673| 15501001 | Only supported in stage mode. |
674| 15501002 | The data group id is not valid. |
675
676**Example**
677
678FA model:
679
680<!--code_no_check_fa-->
681```ts
682// Obtain the context.
683import { featureAbility } from '@kit.AbilityKit';
684import { BusinessError } from '@kit.BasicServicesKit';
685
686let context = featureAbility.getContext();
687
688let options: preferences.Options = { name: 'myStore' };
689let promise = preferences.deletePreferences(context, options);
690promise.then(() => {
691  console.info("Succeeded in deleting preferences.");
692}).catch((err: BusinessError) => {
693  console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
694})
695```
696
697Stage model:
698
699```ts
700import { UIAbility } from '@kit.AbilityKit';
701import { BusinessError } from '@kit.BasicServicesKit';
702import { window } from '@kit.ArkUI';
703
704class EntryAbility extends UIAbility {
705  onWindowStageCreate(windowStage: window.WindowStage) {
706    let options: preferences.Options = { name: 'myStore' };
707    let promise = preferences.deletePreferences(this.context, options);
708    promise.then(() => {
709      console.info("Succeeded in deleting preferences.");
710    }).catch((err: BusinessError) => {
711      console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
712    })
713  }
714}
715```
716
717
718## preferences.removePreferencesFromCache
719
720removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
721
722Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result.
723
724After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
725
726Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
727
728**Atomic service API**: This API can be used in atomic services since API version 11.
729
730**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
731
732**Parameters**
733
734| Name  | Type                                 | Mandatory| Description                                                |
735| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
736| context  | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).                                        |
737| name     | string                                | Yes  | Name of the **Preferences** instance.                             |
738| callback | AsyncCallback&lt;void&gt;             | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
739
740**Error codes**
741
742For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
743
744| ID| Error Message                       |
745| -------- | ------------------------------ |
746| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
747| 15500000 | Inner error.                   |
748
749**Example**
750
751FA model:
752
753<!--code_no_check_fa-->
754```ts
755// Obtain the context.
756import { featureAbility } from '@kit.AbilityKit';
757import { BusinessError } from '@kit.BasicServicesKit';
758
759let context = featureAbility.getContext();
760preferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => {
761  if (err) {
762    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
763    return;
764  }
765  console.info("Succeeded in removing preferences.");
766})
767```
768
769Stage model:
770
771```ts
772import { UIAbility } from '@kit.AbilityKit';
773import { BusinessError } from '@kit.BasicServicesKit';
774import { window } from '@kit.ArkUI';
775
776class EntryAbility extends UIAbility {
777  onWindowStageCreate(windowStage: window.WindowStage) {
778    preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => {
779      if (err) {
780        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
781        return;
782      }
783      console.info("Succeeded in removing preferences.");
784    })
785  }
786}
787```
788
789## preferences.removePreferencesFromCache
790
791removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
792
793Removes a **Preferences** instance from the cache. This API uses a promise to return the result.
794
795After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
796
797Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
798
799**Atomic service API**: This API can be used in atomic services since API version 11.
800
801**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
802
803**Parameters**
804
805| Name | Type                                 | Mandatory| Description                   |
806| ------- | ------------------------------------- | ---- | ----------------------- |
807| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).           |
808| name    | string                                | Yes  | Name of the **Preferences** instance.|
809
810**Return value**
811
812| Type               | Description                     |
813| ------------------- | ------------------------- |
814| Promise&lt;void&gt; | Promise that returns no value.|
815
816**Error codes**
817
818For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
819
820| ID| Error Message                       |
821| -------- | ------------------------------ |
822| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
823| 15500000 | Inner error.                   |
824
825**Example**
826
827FA model:
828
829<!--code_no_check_fa-->
830```ts
831// Obtain the context.
832import { featureAbility } from '@kit.AbilityKit';
833import { BusinessError } from '@kit.BasicServicesKit';
834
835let context = featureAbility.getContext();
836let promise = preferences.removePreferencesFromCache(context, 'myStore');
837promise.then(() => {
838  console.info("Succeeded in removing preferences.");
839}).catch((err: BusinessError) => {
840  console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
841})
842```
843
844Stage model:
845
846```ts
847import { UIAbility } from '@kit.AbilityKit';
848import { BusinessError } from '@kit.BasicServicesKit';
849import { window } from '@kit.ArkUI';
850
851class EntryAbility extends UIAbility {
852  onWindowStageCreate(windowStage: window.WindowStage) {
853    let promise = preferences.removePreferencesFromCache(this.context, 'myStore');
854    promise.then(() => {
855      console.info("Succeeded in removing preferences.");
856    }).catch((err: BusinessError) => {
857      console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
858    })
859  }
860}
861```
862
863## preferences.removePreferencesFromCacheSync<sup>10+</sup>
864
865removePreferencesFromCacheSync(context: Context, name: string): void
866
867Removes a **Preferences** instance from the cache. This API returns the result synchronously.
868
869After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
870
871Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
872
873**Atomic service API**: This API can be used in atomic services since API version 11.
874
875**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
876
877**Parameters**
878
879| Name | Type                                 | Mandatory| Description                   |
880| ------- | ------------------------------------- | ---- | ----------------------- |
881| context | Context | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).           |
882| name    | string                                | Yes  | Name of the **Preferences** instance.|
883
884**Error codes**
885
886For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
887
888| ID| Error Message                       |
889| -------- | ------------------------------ |
890| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
891| 15500000 | Inner error.                   |
892
893**Example**
894
895FA model:
896
897<!--code_no_check_fa-->
898```ts
899// Obtain the context.
900import { featureAbility } from '@kit.AbilityKit';
901let context = featureAbility.getContext();
902preferences.removePreferencesFromCacheSync(context, 'myStore');
903```
904
905Stage model:
906
907```ts
908import { UIAbility } from '@kit.AbilityKit';
909import { window } from '@kit.ArkUI';
910
911class EntryAbility extends UIAbility {
912  onWindowStageCreate(windowStage: window.WindowStage) {
913    preferences.removePreferencesFromCacheSync(this.context, 'myStore');
914  }
915}
916```
917
918## preferences.removePreferencesFromCache<sup>10+</sup>
919
920removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback&lt;void&gt;): void
921
922Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result.
923
924After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
925
926Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
927
928**Atomic service API**: This API can be used in atomic services since API version 11.
929
930**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
931
932**Parameters**
933
934| Name  | Type                     | Mandatory| Description                                                                                                                                                                          |
935| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
936| context  | Context                   | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
937| options  | [Options](#options10)          | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
938| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.                                                                                                                          |
939
940**Error codes**
941
942For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
943
944| ID| Error Message                       |
945| -------- | ------------------------------ |
946| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
947| 801      | Capability not supported.     |
948| 15500000 | Inner error.                   |
949| 15501001 | Only supported in stage mode. |
950| 15501002 | The data group id is not valid.     |
951
952**Example**
953
954FA model:
955
956<!--code_no_check_fa-->
957```ts
958// Obtain the context.
959import { featureAbility } from '@kit.AbilityKit';
960import { BusinessError } from '@kit.BasicServicesKit';
961
962let context = featureAbility.getContext();
963let options: preferences.Options = { name: 'myStore' };
964preferences.removePreferencesFromCache(context, options, (err: BusinessError) => {
965  if (err) {
966    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
967    return;
968  }
969  console.info("Succeeded in removing preferences.");
970})
971```
972
973Stage model:
974
975```ts
976import { UIAbility } from '@kit.AbilityKit';
977import { BusinessError } from '@kit.BasicServicesKit';
978import { window } from '@kit.ArkUI';
979
980class EntryAbility extends UIAbility {
981  onWindowStageCreate(windowStage: window.WindowStage) {
982    let options: preferences.Options = { name: 'myStore' };
983    preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
984      if (err) {
985        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
986        return;
987      }
988      console.info("Succeeded in removing preferences.");
989    })
990  }
991}
992```
993
994## preferences.removePreferencesFromCache<sup>10+</sup>
995
996removePreferencesFromCache(context: Context, options: Options): Promise&lt;void&gt;
997
998Removes a **Preferences** instance from the cache. This API uses a promise to return the result.
999
1000After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
1001
1002Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
1003
1004**Atomic service API**: This API can be used in atomic services since API version 11.
1005
1006**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1007
1008**Parameters**
1009
1010| Name | Type            | Mandatory| Description                                                                                                                                                                          |
1011| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1012| context | Context          | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
1013| options | [Options](#options10) | Yes  | Configuration options of the **Preferences** instance.                                                                                                                                             |
1014
1015**Return value**
1016
1017| Type               | Description                     |
1018| ------------------- | ------------------------- |
1019| Promise&lt;void&gt; | Promise that returns no value.|
1020
1021**Error codes**
1022
1023For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1024
1025| ID| Error Message                       |
1026| -------- | ------------------------------ |
1027| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1028| 801      | Capability not supported.     |
1029| 15500000 | Inner error.                   |
1030| 15501001 | Only supported in stage mode. |
1031| 15501002 | The data group id is not valid.     |
1032
1033**Example**
1034
1035FA model:
1036
1037<!--code_no_check_fa-->
1038```ts
1039// Obtain the context.
1040import { featureAbility } from '@kit.AbilityKit';
1041import { BusinessError } from '@kit.BasicServicesKit';
1042
1043let context = featureAbility.getContext();
1044let options: preferences.Options = { name: 'myStore' };
1045let promise = preferences.removePreferencesFromCache(context, options);
1046promise.then(() => {
1047  console.info("Succeeded in removing preferences.");
1048}).catch((err: BusinessError) => {
1049  console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
1050})
1051```
1052
1053Stage model:
1054
1055```ts
1056import { UIAbility } from '@kit.AbilityKit';
1057import { BusinessError } from '@kit.BasicServicesKit';
1058import { window } from '@kit.ArkUI';
1059
1060class EntryAbility extends UIAbility {
1061  onWindowStageCreate(windowStage: window.WindowStage) {
1062    let options: preferences.Options = { name: 'myStore' };
1063    let promise = preferences.removePreferencesFromCache(this.context, options);
1064    promise.then(() => {
1065      console.info("Succeeded in removing preferences.");
1066    }).catch((err: BusinessError) => {
1067      console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
1068    })
1069  }
1070}
1071```
1072
1073## preferences.removePreferencesFromCacheSync<sup>10+</sup>
1074
1075removePreferencesFromCacheSync(context: Context, options: Options):void
1076
1077Removes a **Preferences** instance from the cache. This API returns the result synchronously.
1078
1079After an application calls [getPreferences](#preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
1080
1081Avoid using a removed **Preferences** instance to perform data operations, which may cause data inconsistency. Instead, set the removed **Preferences** instance to null. The system will reclaim them in a unified manner.
1082
1083**Atomic service API**: This API can be used in atomic services since API version 11.
1084
1085**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1086
1087**Parameters**
1088
1089| Name | Type                 | Mandatory| Description                                                        |
1090| ------- | --------------------- | ---- | ------------------------------------------------------------ |
1091| context | Context               | Yes  | Application context.<br>For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).|
1092| options | [Options](#options10) | Yes  | Configuration options of the **Preferences** instance.                           |
1093
1094**Error codes**
1095
1096For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1097
1098| ID| Error Message                       |
1099| -------- | ------------------------------ |
1100| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1101| 801      | Capability not supported.     |
1102| 15500000 | Inner error.                   |
1103| 15501001 | Only supported in stage mode.   |
1104| 15501002 | The data group id is not valid. |
1105
1106**Example**
1107
1108FA model:
1109
1110<!--code_no_check_fa-->
1111```ts
1112// Obtain the context.
1113import { featureAbility } from '@kit.AbilityKit';
1114let context = featureAbility.getContext();
1115let options: preferences.Options = { name: 'myStore' };
1116preferences.removePreferencesFromCacheSync(context, options);
1117```
1118
1119Stage model:
1120
1121```ts
1122import { UIAbility } from '@kit.AbilityKit';
1123import { window } from '@kit.ArkUI';
1124
1125class EntryAbility extends UIAbility {
1126  onWindowStageCreate(windowStage: window.WindowStage) {
1127    let options: preferences.Options = { name: 'myStore' };
1128    preferences.removePreferencesFromCacheSync(this.context, options);
1129  }
1130}
1131```
1132
1133## Options<sup>10+</sup>
1134
1135Represents the configuration of a **Preferences** instance.
1136
1137**Atomic service API**: This API can be used in atomic services since API version 11.
1138
1139**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1140
1141| Name       | Type  | Mandatory| Description                                                        |
1142| ----------- | ------ | ---- | ------------------------------------------------------------ |
1143| name        | string | Yes  | Name of the **Preferences** instance.                                     |
1144| dataGroupId | string\|null\|undefined | No  | Application group ID, which needs to be obtained from AppGallery. This parameter is not supported currently.<br>This parameter is optional. A **Preferences** instance will be created in the sandbox path corresponding to the specified **dataGroupId**. If this parameter is not specified, the **Preferences** instance is created in the sandbox directory of the application.<br> **Model restriction**: This attribute can be used only in the stage model.|
1145
1146
1147## Preferences
1148
1149Provides APIs for obtaining and modifying the stored data.
1150
1151Before calling any API of **Preferences**, you must obtain a **Preferences** instance by using [preferences.getPreferences](#preferencesgetpreferences).
1152
1153
1154### get
1155
1156get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void
1157
1158Obtains the value of a key from this **Preferences** instance. This API uses an asynchronous callback to return the result. If the value is null or is not of the default value type, **defValue** is returned.
1159
1160**Atomic service API**: This API can be used in atomic services since API version 11.
1161
1162**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1163
1164**Parameters**
1165
1166| Name  | Type                                        | Mandatory| Description              |
1167| -------- | -------------------------------------------- | ---- |---------------------------|
1168| key      | string                                       | Yes  | Key of the data to obtain. It cannot be empty.  |
1169| defValue | [ValueType](#valuetype)                      | Yes  | Default value to be returned.|
1170| callback | AsyncCallback&lt;[ValueType](#valuetype)&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the value obtained. Otherwise, **err** is an error object.  |
1171
1172**Error codes**
1173
1174For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1175
1176| ID| Error Message                       |
1177| -------- | ------------------------------ |
1178| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1179| 15500000 | Inner error.                   |
1180
1181**Example**
1182
1183```ts
1184import { BusinessError } from '@kit.BasicServicesKit';
1185
1186dataPreferences.get('startup', 'default', (err: BusinessError, val: preferences.ValueType) => {
1187  if (err) {
1188    console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
1189    return;
1190  }
1191  console.info("Obtained the value of 'startup' successfully. val: " + val);
1192})
1193```
1194
1195### get
1196
1197get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
1198
1199Obtains the value of a key from this **Preferences** instance. This API uses a promise to return the result. If the value is null or is not of the default value type, **defValue** is returned.
1200
1201**Atomic service API**: This API can be used in atomic services since API version 11.
1202
1203**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1204
1205 **Parameters**
1206
1207| Name  | Type                   | Mandatory| Description |
1208| -------- | ----------------------- | ---- |--------|
1209| key      | string                  | Yes  | Key of the data to obtain. It cannot be empty. |
1210| defValue | [ValueType](#valuetype) | Yes  | Default value to be returned.|
1211
1212**Return value**
1213
1214| Type                               | Description                         |
1215| ----------------------------------- | ----------------------------- |
1216| Promise<[ValueType](#valuetype)&gt; | Promise used to return the value obtained.|
1217
1218**Error codes**
1219
1220For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1221
1222| ID| Error Message                       |
1223| -------- | ------------------------------ |
1224| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1225| 15500000 | Inner error.                   |
1226
1227**Example**
1228
1229```ts
1230import { BusinessError } from '@kit.BasicServicesKit';
1231
1232let promise = dataPreferences.get('startup', 'default');
1233promise.then((data: preferences.ValueType) => {
1234  console.info("Got the value of 'startup'. Data: " + data);
1235}).catch((err: BusinessError) => {
1236  console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
1237})
1238```
1239
1240### getSync<sup>10+</sup>
1241
1242getSync(key: string, defValue: ValueType): ValueType
1243
1244Obtains the value of a key from this **Preferences** instance. This API returns the result synchronously. If the value is null or is not of the default value type, **defValue** is returned.
1245
1246**Atomic service API**: This API can be used in atomic services since API version 11.
1247
1248**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1249
1250**Parameters**
1251
1252| Name  | Type                   | Mandatory| Description           |
1253| -------- | ----------------------- | ---- |---------------------|
1254| key      | string                  | Yes  | Key of the data to obtain. It cannot be empty. |
1255| defValue | [ValueType](#valuetype) | Yes  | Default value to be returned.|
1256
1257**Return value**
1258
1259| Type                               | Description                         |
1260| ----------------------------------- | ----------------------------- |
1261| [ValueType](#valuetype) | Returns the value obtained.|
1262
1263**Error codes**
1264
1265For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1266
1267| ID| Error Message                       |
1268| -------- | ------------------------------ |
1269| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1270| 15500000 | Inner error.                   |
1271
1272**Example**
1273
1274```ts
1275let value: preferences.ValueType = dataPreferences.getSync('startup', 'default');
1276```
1277
1278### getAll
1279
1280getAll(callback: AsyncCallback&lt;Object&gt;): void;
1281
1282Obtains all KV pairs from this **Preferences** instance. This API uses an asynchronous callback to return the result.
1283
1284**Atomic service API**: This API can be used in atomic services since API version 11.
1285
1286**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1287
1288**Parameters**
1289
1290| Name  | Type                       | Mandatory| Description                                                        |
1291| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
1292| callback | AsyncCallback&lt;Object&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **value** provides all KV pairs obtained. Otherwise, **err** is an error object.|
1293
1294**Error codes**
1295
1296For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1297
1298| ID| Error Message                       |
1299| -------- | ------------------------------ |
1300| 401      | Parameter error. Mandatory parameters are left unspecified.|
1301| 15500000 | Inner error.                   |
1302
1303**Example**
1304
1305```ts
1306import { BusinessError } from '@kit.BasicServicesKit';
1307
1308// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
1309// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
1310function getObjKeys(obj: Object): string[] {
1311  let keys = Object.keys(obj);
1312  return keys;
1313}
1314
1315dataPreferences.getAll((err: BusinessError, value: Object) => {
1316  if (err) {
1317    console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
1318    return;
1319  }
1320  let allKeys = getObjKeys(value);
1321  console.info("getAll keys = " + allKeys);
1322  console.info("getAll object = " + JSON.stringify(value));
1323})
1324```
1325
1326
1327### getAll
1328
1329getAll(): Promise&lt;Object&gt;
1330
1331Obtains all KV pairs from this **Preferences** instance. This API uses a promise to return the result.
1332
1333**Atomic service API**: This API can be used in atomic services since API version 11.
1334
1335**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1336
1337**Return value**
1338
1339| Type                 | Description                                       |
1340| --------------------- | ------------------------------------------- |
1341| Promise&lt;Object&gt; | Promise used to return the KV pairs obtained.|
1342
1343**Error codes**
1344
1345For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
1346
1347| ID| Error Message                       |
1348| -------- | ------------------------------ |
1349| 15500000 | Inner error.                   |
1350
1351**Example**
1352
1353```ts
1354import { BusinessError } from '@kit.BasicServicesKit';
1355
1356// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
1357// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
1358function getObjKeys(obj: Object): string[] {
1359  let keys = Object.keys(obj);
1360  return keys;
1361}
1362
1363let promise = dataPreferences.getAll();
1364promise.then((value: Object) => {
1365  let allKeys = getObjKeys(value);
1366  console.info('getAll keys = ' + allKeys);
1367  console.info("getAll object = " + JSON.stringify(value));
1368}).catch((err: BusinessError) => {
1369  console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
1370})
1371```
1372
1373### getAllSync<sup>10+</sup>
1374
1375getAllSync(): Object
1376
1377Obtains all KV pairs from this **Preferences** instance. This API returns the result synchronously.
1378
1379**Atomic service API**: This API can be used in atomic services since API version 11.
1380
1381**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1382
1383**Return value**
1384
1385| Type                 | Description                                       |
1386| --------------------- | ------------------------------------------- |
1387| Object | Returns all KV pairs obtained.|
1388
1389**Error codes**
1390
1391For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
1392
1393| ID| Error Message                       |
1394| -------- | ------------------------------ |
1395| 15500000 | Inner error.                   |
1396
1397**Example**
1398
1399```ts
1400// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used.
1401// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required.
1402function getObjKeys(obj: Object): string[] {
1403  let keys = Object.keys(obj);
1404  return keys;
1405}
1406
1407let value = dataPreferences.getAllSync();
1408let allKeys = getObjKeys(value);
1409console.info('getAll keys = ' + allKeys);
1410console.info("getAll object = " + JSON.stringify(value));
1411```
1412
1413### put
1414
1415put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
1416
1417Writes data to this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1418
1419  > **NOTE**
1420  >
1421  > If the key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
1422
1423**Atomic service API**: This API can be used in atomic services since API version 11.
1424
1425**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1426
1427**Parameters**
1428
1429| Name  | Type                     | Mandatory| Description                      |
1430| -------- | ------------------------- | ---- |-------------------------|
1431| key      | string                    | Yes  | Key of the data. It cannot be empty.|
1432| value    | [ValueType](#valuetype)   | Yes  | Value to write.|
1433| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
1434
1435**Error codes**
1436
1437For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1438
1439| ID| Error Message                       |
1440| -------- | ------------------------------ |
1441| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1442| 15500000 | Inner error.                   |
1443
1444**Example**
1445
1446```ts
1447import { BusinessError } from '@kit.BasicServicesKit';
1448
1449dataPreferences.put('startup', 'auto', (err: BusinessError) => {
1450  if (err) {
1451    console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
1452    return;
1453  }
1454  console.info("Successfully put the value of 'startup'.");
1455})
1456```
1457
1458
1459### put
1460
1461put(key: string, value: ValueType): Promise&lt;void&gt;
1462
1463Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1464
1465  > **NOTE**
1466  >
1467  > If the key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
1468
1469**Atomic service API**: This API can be used in atomic services since API version 11.
1470
1471**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1472
1473**Parameters**
1474
1475| Name| Type                   | Mandatory| Description                        |
1476| ------ | ----------------------- | ---- |--------------------------|
1477| key    | string                  | Yes  | Key of the data. It cannot be empty. |
1478| value  | [ValueType](#valuetype) | Yes  | Value to write.|
1479
1480**Return value**
1481
1482| Type               | Description                     |
1483| ------------------- | ------------------------- |
1484| Promise&lt;void&gt; | Promise that returns no value.|
1485
1486**Error codes**
1487
1488For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1489
1490| ID| Error Message                       |
1491| -------- | ------------------------------ |
1492| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1493| 15500000 | Inner error.                   |
1494
1495**Example**
1496
1497```ts
1498import { BusinessError } from '@kit.BasicServicesKit';
1499
1500let promise = dataPreferences.put('startup', 'auto');
1501promise.then(() => {
1502  console.info("Successfully put the value of 'startup'.");
1503}).catch((err: BusinessError) => {
1504  console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
1505})
1506```
1507
1508
1509### putSync<sup>10+</sup>
1510
1511putSync(key: string, value: ValueType): void
1512
1513Writes data to this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
1514
1515  > **NOTE**
1516  >
1517  > If the key already exists, **putSync()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists.
1518
1519**Atomic service API**: This API can be used in atomic services since API version 11.
1520
1521**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1522
1523**Parameters**
1524
1525| Name| Type                   | Mandatory| Description                                                        |
1526| ------ | ----------------------- | ---- | ------------------------ |
1527| key    | string                  | Yes  | Key of the data. It cannot be empty.|
1528| value  | [ValueType](#valuetype) | Yes  | Value to write.|
1529
1530**Error codes**
1531
1532For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1533
1534| ID| Error Message                       |
1535| -------- | ------------------------------ |
1536| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1537| 15500000 | Inner error.                   |
1538
1539**Example**
1540
1541```ts
1542dataPreferences.putSync('startup', 'auto');
1543```
1544
1545
1546### has
1547
1548has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
1549
1550Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses an asynchronous callback to return the result.
1551
1552**Atomic service API**: This API can be used in atomic services since API version 11.
1553
1554**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1555
1556**Parameters**
1557
1558| Name  | Type                        | Mandatory| Description                                                        |
1559| -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
1560| key      | string                       | Yes  | Key of the data to check. It cannot be empty.                             |
1561| callback | AsyncCallback&lt;boolean&gt; | Yes  | Callback used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.|
1562
1563**Error codes**
1564
1565For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1566
1567| ID| Error Message                       |
1568| -------- | ------------------------------ |
1569| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1570| 15500000 | Inner error.                   |
1571
1572**Example**
1573
1574```ts
1575import { BusinessError } from '@kit.BasicServicesKit';
1576
1577dataPreferences.has('startup', (err: BusinessError, val: boolean) => {
1578  if (err) {
1579    console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
1580    return;
1581  }
1582  if (val) {
1583    console.info("The key 'startup' is contained.");
1584  } else {
1585    console.info("The key 'startup' is not contained.");
1586  }
1587})
1588```
1589
1590
1591### has
1592
1593has(key: string): Promise&lt;boolean&gt;
1594
1595Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result.
1596
1597**Atomic service API**: This API can be used in atomic services since API version 11.
1598
1599**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1600
1601**Parameters**
1602
1603| Name| Type  | Mandatory| Description                           |
1604| ------ | ------ | ---- | ------------------------------- |
1605| key    | string | Yes  | Key of the data to check. It cannot be empty.|
1606
1607**Return value**
1608
1609| Type                  | Description                                                        |
1610| ---------------------- | ------------------------------------------------------------ |
1611| Promise&lt;boolean&gt; | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.|
1612
1613**Error codes**
1614
1615For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1616
1617| ID| Error Message                       |
1618| -------- | ------------------------------ |
1619| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1620| 15500000 | Inner error.                   |
1621
1622**Example**
1623
1624```ts
1625import { BusinessError } from '@kit.BasicServicesKit';
1626
1627let promise = dataPreferences.has('startup');
1628promise.then((val: boolean) => {
1629  if (val) {
1630    console.info("The key 'startup' is contained.");
1631  } else {
1632    console.info("The key 'startup' is not contained.");
1633  }
1634}).catch((err: BusinessError) => {
1635  console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
1636})
1637```
1638
1639
1640### hasSync<sup>10+</sup>
1641
1642hasSync(key: string): boolean
1643
1644Checks whether this **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously.
1645
1646**Atomic service API**: This API can be used in atomic services since API version 11.
1647
1648**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1649
1650**Parameters**
1651
1652| Name| Type  | Mandatory| Description                           |
1653| ------ | ------ | ---- | ------------------------------- |
1654| key    | string | Yes  | Key of the data to check. It cannot be empty.|
1655
1656**Return value**
1657
1658| Type                  | Description                                                        |
1659| ---------------------- | ------------------------------------------------------------ |
1660| boolean | If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.|
1661
1662**Error codes**
1663
1664For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1665
1666| ID| Error Message                       |
1667| -------- | ------------------------------ |
1668| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1669| 15500000 | Inner error.                   |
1670
1671**Example**
1672
1673```ts
1674let isExist: boolean = dataPreferences.hasSync('startup');
1675if (isExist) {
1676  console.info("The key 'startup' is contained.");
1677} else {
1678  console.info("The key 'startup' is not contained.");
1679}
1680```
1681
1682
1683### delete
1684
1685delete(key: string, callback: AsyncCallback&lt;void&gt;): void
1686
1687Deletes a KV pair from this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1688
1689**Atomic service API**: This API can be used in atomic services since API version 11.
1690
1691**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1692
1693**Parameters**
1694
1695| Name  | Type                     | Mandatory| Description                                                |
1696| -------- | ------------------------- | ---- | ---------------------------------------------------- |
1697| key      | string                    | Yes  | Key of the KV pair to delete. It cannot be empty.                     |
1698| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
1699
1700**Error codes**
1701
1702For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1703
1704| ID| Error Message                       |
1705| -------- | ------------------------------ |
1706| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1707| 15500000 | Inner error.                   |
1708
1709**Example**
1710
1711```ts
1712import { BusinessError } from '@kit.BasicServicesKit';
1713
1714dataPreferences.delete('startup', (err: BusinessError) => {
1715  if (err) {
1716    console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
1717    return;
1718  }
1719  console.info("Deleted the key 'startup'.");
1720})
1721```
1722
1723
1724### delete
1725
1726delete(key: string): Promise&lt;void&gt;
1727
1728Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1729
1730**Atomic service API**: This API can be used in atomic services since API version 11.
1731
1732**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1733
1734**Parameters**
1735
1736| Name| Type  | Mandatory| Description                           |
1737| ------ | ------ | ---- | ------------------------------- |
1738| key    | string | Yes  | Key of the KV pair to delete. It cannot be empty.|
1739
1740**Return value**
1741
1742| Type               | Description                     |
1743| ------------------- | ------------------------- |
1744| Promise&lt;void&gt; | Promise that returns no value.|
1745
1746**Error codes**
1747
1748For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1749
1750| ID| Error Message                       |
1751| -------- | ------------------------------ |
1752| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1753| 15500000 | Inner error.                   |
1754
1755**Example**
1756
1757```ts
1758import { BusinessError } from '@kit.BasicServicesKit';
1759
1760let promise = dataPreferences.delete('startup');
1761promise.then(() => {
1762  console.info("Deleted the key 'startup'.");
1763}).catch((err: BusinessError) => {
1764  console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
1765})
1766```
1767
1768
1769### deleteSync<sup>10+</sup>
1770
1771deleteSync(key: string): void
1772
1773Deletes a KV pair from this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
1774
1775**Atomic service API**: This API can be used in atomic services since API version 11.
1776
1777**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1778
1779**Parameters**
1780
1781| Name| Type  | Mandatory| Description                           |
1782| ------ | ------ | ---- | ------------------------------- |
1783| key    | string | Yes  | Key of the KV pair to delete. It cannot be empty.|
1784
1785**Error codes**
1786
1787For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1788
1789| ID| Error Message                       |
1790| -------- | ------------------------------ |
1791| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
1792| 15500000 | Inner error.                   |
1793
1794**Example**
1795
1796```ts
1797dataPreferences.deleteSync('startup');
1798```
1799
1800
1801### flush
1802
1803flush(callback: AsyncCallback&lt;void&gt;): void
1804
1805Flushes the data in this **Preferences** instance to the persistent file. This API uses an asynchronous callback to return the result.
1806
1807**Atomic service API**: This API can be used in atomic services since API version 11.
1808
1809**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1810
1811**Parameters**
1812
1813| Name  | Type                     | Mandatory| Description                                                |
1814| -------- | ------------------------- | ---- | ---------------------------------------------------- |
1815| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
1816
1817**Error codes**
1818
1819For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1820
1821| ID| Error Message                       |
1822| -------- | ------------------------------ |
1823| 401      | Parameter error. Mandatory parameters are left unspecified.                       |
1824| 15500000 | Inner error.                   |
1825
1826**Example**
1827
1828```ts
1829import { BusinessError } from '@kit.BasicServicesKit';
1830
1831dataPreferences.flush((err: BusinessError) => {
1832  if (err) {
1833    console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
1834    return;
1835  }
1836  console.info("Successfully flushed data.");
1837})
1838```
1839
1840
1841### flush
1842
1843flush(): Promise&lt;void&gt;
1844
1845Flushes the data in this **Preferences** instance to the persistent file. This API uses a promise to return the result.
1846
1847**Atomic service API**: This API can be used in atomic services since API version 11.
1848
1849**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1850
1851**Return value**
1852
1853| Type               | Description                     |
1854| ------------------- | ------------------------- |
1855| Promise&lt;void&gt; | Promise that returns no value.|
1856
1857**Error codes**
1858
1859For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
1860
1861| ID| Error Message                       |
1862| -------- | ------------------------------ |
1863| 15500000 | Inner error.                   |
1864
1865**Example**
1866
1867```ts
1868import { BusinessError } from '@kit.BasicServicesKit';
1869
1870let promise = dataPreferences.flush();
1871promise.then(() => {
1872  console.info("Successfully flushed data.");
1873}).catch((err: BusinessError) => {
1874  console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
1875})
1876```
1877
1878### flushSync<sup>14+</sup>
1879
1880flushSync(): void
1881
1882Flushes the data in the cached **Preferences** instance to the persistent file.
1883
1884**Atomic service API**: This API can be used in atomic services since API version 14.
1885
1886**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1887
1888**Error codes**
1889
1890For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
1891
1892| ID| Error Message                       |
1893| -------- | ------------------------------ |
1894| 15500000 | Inner error.                   |
1895
1896**Example**
1897
1898```ts
1899dataPreferences.flushSync();
1900```
1901
1902### clear
1903
1904clear(callback: AsyncCallback&lt;void&gt;): void
1905
1906Clears this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1907
1908**Atomic service API**: This API can be used in atomic services since API version 11.
1909
1910**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1911
1912**Parameters**
1913
1914| Name  | Type                     | Mandatory| Description                                                |
1915| -------- | ------------------------- | ---- | ---------------------------------------------------- |
1916| callback | AsyncCallback&lt;void&gt; | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
1917
1918**Error codes**
1919
1920For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
1921
1922| ID| Error Message                       |
1923| -------- | ------------------------------ |
1924| 401      | Parameter error. Mandatory parameters are left unspecified.                       |
1925| 15500000 | Inner error.                   |
1926
1927**Example**
1928
1929```ts
1930import { BusinessError } from '@kit.BasicServicesKit';
1931
1932dataPreferences.clear((err: BusinessError) =>{
1933  if (err) {
1934    console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
1935    return;
1936  }
1937  console.info("Successfully cleared data.");
1938})
1939```
1940
1941
1942### clear
1943
1944clear(): Promise&lt;void&gt;
1945
1946Clears this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance.
1947
1948**Atomic service API**: This API can be used in atomic services since API version 11.
1949
1950**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1951
1952**Return value**
1953
1954| Type               | Description                     |
1955| ------------------- | ------------------------- |
1956| Promise&lt;void&gt; | Promise that returns no value.|
1957
1958**Error codes**
1959
1960For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md).
1961
1962| ID| Error Message                       |
1963| -------- | ------------------------------ |
1964| 15500000 | Inner error.                   |
1965
1966**Example**
1967
1968```ts
1969import { BusinessError } from '@kit.BasicServicesKit';
1970
1971let promise = dataPreferences.clear();
1972promise.then(() => {
1973  console.info("Successfully cleared data.");
1974}).catch((err: BusinessError) => {
1975  console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
1976})
1977```
1978
1979
1980### clearSync<sup>10+</sup>
1981
1982clearSync(): void
1983
1984Clears this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance.
1985
1986**Atomic service API**: This API can be used in atomic services since API version 11.
1987
1988**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
1989
1990**Example**
1991
1992```ts
1993dataPreferences.clearSync();
1994```
1995
1996
1997### on('change')
1998
1999on(type: 'change', callback: Callback&lt;string&gt;): void
2000
2001Subscribes to data changes. The registered callback will be invoked to return the new value if the data change is [flushed](#flush).
2002
2003**Atomic service API**: This API can be used in atomic services since API version 11.
2004
2005**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2006
2007**Parameters**
2008
2009| Name  | Type    | Mandatory| Description                                    |
2010| -------- | -------- | ---- | ---------------------------------------- |
2011| type     | string   | Yes  | Event type. The value is **'change'**, which indicates data changes.|
2012| callback | Callback&lt;string&gt; | Yes  | Callback used to return the data change.    |
2013
2014**Error codes**
2015
2016For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2017
2018| ID| Error Message                       |
2019| -------- | ------------------------------ |
2020| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2021| 15500000 | Inner error.                   |
2022
2023**Example**
2024
2025```ts
2026import { BusinessError } from '@kit.BasicServicesKit';
2027
2028let observer = (key: string) => {
2029  console.info("The key " + key + " changed.");
2030}
2031dataPreferences.on('change', observer);
2032dataPreferences.putSync('startup', 'manual');
2033dataPreferences.flush((err: BusinessError) => {
2034  if (err) {
2035    console.error("Failed to flush. Cause: " + err);
2036    return;
2037  }
2038  console.info("Successfully flushed data.");
2039})
2040```
2041
2042### on('multiProcessChange')<sup>10+</sup>
2043
2044on(type: 'multiProcessChange', callback: Callback&lt;string&gt;): void
2045
2046Subscribes to inter-process data changes. For the multiple processes holding the same preference file, if the value of the subscribed key changes in any process, the callback in this API will be invoked after [flush()](#flush) is executed.
2047
2048**Atomic service API**: This API can be used in atomic services since API version 11.
2049
2050**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2051
2052**Parameters**
2053
2054| Name  | Type    | Mandatory| Description                                                        |
2055| -------- | -------- | ---- | ------------------------------------------------------------ |
2056| type     | string   | Yes  | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.|
2057| callback | Callback&lt;string&gt; | Yes  | Callback used to return the data change.                        |
2058
2059**Error codes**
2060
2061For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2062
2063| ID| Error Message                               |
2064| -------- | -------------------------------------- |
2065| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2066| 15500000 | Inner error.                           |
2067| 15500019 | Failed to obtain subscription service. |
2068
2069**Example**
2070
2071```ts
2072import { BusinessError } from '@kit.BasicServicesKit';
2073
2074let observer = (key: string) => {
2075  console.info("The key " + key + " changed.");
2076}
2077dataPreferences.on('multiProcessChange', observer);
2078dataPreferences.putSync('startup', 'manual');
2079dataPreferences.flush((err: BusinessError) => {
2080  if (err) {
2081    console.error("Failed to flush. Cause: " + err);
2082    return;
2083  }
2084  console.info("Successfully flushed data.");
2085})
2086```
2087
2088### on('dataChange')<sup>12+</sup>
2089
2090on(type: 'dataChange', keys: Array&lt;string&gt;,  callback: Callback&lt;Record&lt;string, ValueType&gt;&gt;): void
2091
2092Subscribes to changes of specific data. The registered callback will be invoked only after the values of the specified keys are changed and [flushed](#flush).
2093
2094**Atomic service API**: This API can be used in atomic services since API version 12.
2095
2096**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2097
2098**Parameters**
2099
2100| Name  | Type                                                        | Mandatory| Description                                                        |
2101| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2102| type     | string                                                       | Yes  | Event type. The value is **'dataChange'**, which indicates data changes.          |
2103| keys     | Array&lt;string&gt;                                          | Yes  | Array of the keys to be observed.                                         |
2104| callback | Callback&lt;Record&lt;string, [ValueType](#valuetype)&gt;&gt; | Yes  | Callback used to return the changed data, in an array of KV pairs. The keys identify the data changed, and the values are the new values. The values support the following data types: number, string, boolean, Array\<number>, Array\<string>, Array\< boolean>, Uint8Array, and object.|
2105
2106**Error codes**
2107
2108For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2109
2110| ID| Error Message                       |
2111| -------- | ------------------------------ |
2112| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2113| 15500000 | Inner error.                   |
2114
2115**Example**
2116
2117```ts
2118import { BusinessError } from '@kit.BasicServicesKit';
2119
2120let observer = (data: Record<string, preferences.ValueType>) => {
2121  for (const keyValue of Object.entries(data)) {
2122    console.info(`observer : ${keyValue}`)
2123  }
2124  console.info("The observer called.")
2125}
2126let keys = ['name', 'age']
2127dataPreferences.on('dataChange', keys, observer);
2128dataPreferences.putSync('name', 'xiaohong');
2129dataPreferences.putSync('weight', 125);
2130dataPreferences.flush((err: BusinessError) => {
2131  if (err) {
2132    console.error("Failed to flush. Cause: " + err);
2133    return;
2134  }
2135  console.info("Successfully flushed data.");
2136})
2137```
2138
2139### off('change')
2140
2141off(type: 'change', callback?: Callback&lt;string&gt;): void
2142
2143Unsubscribes from data changes.
2144
2145**Atomic service API**: This API can be used in atomic services since API version 11.
2146
2147**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2148
2149**Parameters**
2150
2151| Name  | Type    | Mandatory| Description                                                        |
2152| -------- | -------- | ---- | ------------------------------------------------------------ |
2153| type     | string   | Yes  | Event type. The value is **'change'**, which indicates data changes.                    |
2154| callback | Callback&lt;string&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.|
2155
2156**Error codes**
2157
2158For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2159
2160| ID| Error Message                       |
2161| -------- | ------------------------------ |
2162| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2163| 15500000 | Inner error.                   |
2164
2165**Example**
2166
2167```ts
2168import { BusinessError } from '@kit.BasicServicesKit';
2169
2170let observer = (key: string) => {
2171  console.info("The key " + key + " changed.");
2172}
2173dataPreferences.on('change', observer);
2174dataPreferences.putSync('startup', 'auto');
2175dataPreferences.flush((err: BusinessError) => {
2176  if (err) {
2177    console.error("Failed to flush. Cause: " + err);
2178    return;
2179  }
2180  console.info("Successfully flushed data.");
2181})
2182dataPreferences.off('change', observer);
2183```
2184
2185### off('multiProcessChange')<sup>10+</sup>
2186
2187off(type: 'multiProcessChange', callback?: Callback&lt;string&gt;): void
2188
2189Unsubscribes from inter-process data changes.
2190
2191**Atomic service API**: This API can be used in atomic services since API version 11.
2192
2193**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2194
2195**Parameters**
2196
2197| Name  | Type    | Mandatory| Description                                                        |
2198| -------- | -------- | ---- | ------------------------------------------------------------ |
2199| type     | string   | Yes  | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.|
2200| callback | Callback&lt;string&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.|
2201
2202**Error codes**
2203
2204For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2205
2206| ID| Error Message                       |
2207| -------- | ------------------------------ |
2208| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2209| 15500000 | Inner error.                   |
2210
2211**Example**
2212
2213```ts
2214import { BusinessError } from '@kit.BasicServicesKit';
2215
2216let observer = (key: string) => {
2217  console.info("The key " + key + " changed.");
2218}
2219dataPreferences.on('multiProcessChange', observer);
2220dataPreferences.putSync('startup', 'auto');
2221dataPreferences.flush((err: BusinessError) => {
2222  if (err) {
2223    console.error("Failed to flush. Cause: " + err);
2224    return;
2225  }
2226  console.info("Successfully flushed data.");
2227})
2228dataPreferences.off('multiProcessChange', observer);
2229```
2230### off('dataChange')<sup>12+</sup>
2231
2232off(type: 'dataChange', keys: Array&lt;string&gt;,  callback?: Callback&lt;Record&lt;string, ValueType&gt;&gt;): void
2233
2234Unsubscribes from changes of specific data.
2235
2236**Atomic service API**: This API can be used in atomic services since API version 12.
2237
2238**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2239
2240**Parameters**
2241
2242| Name  | Type                                                        | Mandatory| Description                                                        |
2243| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2244| type     | string                                                       | Yes  | Event type. The value is **'dataChange'**, which indicates data changes.          |
2245| keys     | Array&lt;string&gt;                                          | Yes  | Array of keys to be unsubscribed from. If this parameter is left empty, all keys are unsubscribed from.|
2246| callback | Callback&lt;Record&lt;string, [ValueType](#valuetype)&gt;&gt; | No  | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the changes of the specified data.|
2247
2248**Error codes**
2249
2250For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md).
2251
2252| ID| Error Message                       |
2253| -------- | ------------------------------ |
2254| 401      | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.                       |
2255| 15500000 | Inner error.                   |
2256
2257**Example**
2258
2259```ts
2260import { BusinessError } from '@kit.BasicServicesKit';
2261
2262let observer = (data: Record<string, preferences.ValueType>) => {
2263  for (const keyValue of Object.entries(data)) {
2264    console.info(`observer : ${keyValue}`)
2265  }
2266  console.info("The observer called.")
2267}
2268let keys = ['name', 'age']
2269dataPreferences.on('dataChange', keys, observer);
2270dataPreferences.putSync('name', 'xiaohong');
2271dataPreferences.putSync('weight', 125);
2272dataPreferences.flush((err: BusinessError) => {
2273  if (err) {
2274    console.error("Failed to flush. Cause: " + err);
2275    return;
2276  }
2277  console.info("Successfully flushed data.");
2278})
2279dataPreferences.off('dataChange', keys, observer);
2280```
2281
2282## ValueType
2283
2284type ValueType = number | string | boolean | Array\<number> | Array\<string> | Array\<boolean> | Uint8Array | object | bigint
2285
2286Enumerates the value types.
2287
2288**Atomic service API**: This API can be used in atomic services since API version 11.
2289
2290**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
2291
2292| Type                      | Description               |
2293|--------------------------|-------------------|
2294| number                   | The value is a number.        |
2295| string                   | The value is a string.       |
2296| boolean                  | The value is true or false.       |
2297| Array\<number>           | The value is an array of numbers.   |
2298| Array\<boolean>          | The value is a Boolean array.   |
2299| Array\<string>           | The value is an array of strings.  |
2300| Uint8Array<sup>11+</sup> | The value is an array of 8-bit unsigned integers.|
2301| object<sup>12+</sup>     | The value is an object.|
2302| bigint<sup>12+</sup>     | The value is an integer in any format. |
2303