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