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