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-paths) 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 | Read-Only| Description | 28| ---------------- | -------- | ---- | --------------------------------------- | 29| MAX_KEY_LENGTH | number | Yes | Maximum key length, which is 1024 bytes. | 30| MAX_VALUE_LENGTH | number | Yes | 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 specified **Preferences** instance from the cache. If the **Preferences** instance has a corresponding persistent file, the persistent file is also deleted. This API uses an asynchronous callback to return the result. 413 414Avoid 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. 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 specified **Preferences** instance from the cache. If the **Preferences** instance has a corresponding persistent file, the persistent file is also deleted. This API uses a promise to return the result. 486 487Avoid 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. 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 specified **Preferences** instance from the cache. If the **Preferences** instance has a corresponding persistent file, the persistent file is also deleted. This API uses an asynchronous callback to return the result. 562 563Avoid 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. 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 specified **Preferences** instance from the cache. If the **Preferences** instance has a corresponding persistent file, the persistent file is also deleted. This API uses a promise to return the result. 641 642Avoid 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. 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 **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 **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 **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 **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 **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 **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>18+</sup> 1134Enumerates the storage types of preferences. 1135 1136**Atomic service API**: This API can be used in atomic services since API version 18. 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| GSKV | 1 |GSKV.<br>Data is stored in GSKV 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>18+</sup> 1153isStorageTypeSupported(type: StorageType): boolean 1154 1155Checks whether the specified storage type is supported. This API returns the result synchronously. If the storage type is supported, **true** is returned. Otherwise, **false** is returned. 1156 1157**Atomic service API**: This API can be used in atomic services since API version 18. 1158 1159**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1160 1161**Parameters** 1162 1163| Name | Type | Mandatory| Description | 1164| ------- | --------------------- | ---- | ------------------------------------------------------------ | 1165| type | [StorageType](#storagetype18) | Yes | Storage type to check.| 1166 1167**Return value** 1168 1169| Type | Description | 1170| ------------------- | ------------------------- | 1171| boolean | Returns **true** if the storage type is supported; returns **false** otherwise.| 1172 1173**Error codes** 1174 1175For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1176 1177| ID| Error Message | 1178| -------- | ------------------------------ | 1179| 401 | Parameter error. Possible causes: Incorrect parameter types. | 1180 1181 1182**Example** 1183 1184```ts 1185let xmlType = preferences.StorageType.XML; 1186let gskvType = preferences.StorageType.GSKV; 1187let isXmlSupported = preferences.isStorageTypeSupported(xmlType); 1188let isGskvSupported = preferences.isStorageTypeSupported(gskvType); 1189console.info("Is xml supported in current platform: " + isXmlSupported); 1190console.info("Is gskv supported in current platform: " + isGskvSupported); 1191``` 1192 1193## Options<sup>10+</sup> 1194 1195Represents the configuration of a **Preferences** instance. 1196 1197**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1198 1199| Name | Type | Mandatory| Description | 1200| ----------- | ------ | ---- | ------------------------------------------------------------ | 1201| 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. | 1202| 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. | 1203| storageType<sup>18+</sup> | [StorageType](#storagetype18)\|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 18. | 1204 1205 1206## Preferences 1207 1208Provides APIs for obtaining and modifying the stored data. 1209 1210Before calling any API of **Preferences**, you must obtain a **Preferences** instance by using [preferences.getPreferences](#preferencesgetpreferences). 1211 1212 1213### get 1214 1215get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void 1216 1217Obtains 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. 1218 1219**Atomic service API**: This API can be used in atomic services since API version 11. 1220 1221**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1222 1223**Parameters** 1224 1225| Name | Type | Mandatory| Description | 1226| -------- | -------------------------------------------- | ---- |---------------------------| 1227| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1228| defValue | [ValueType](#valuetype) | Yes | Default value to be returned.| 1229| 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. | 1230 1231**Error codes** 1232 1233For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1234 1235| ID| Error Message | 1236| -------- | ------------------------------ | 1237| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1238| 15500000 | Inner error. | 1239 1240**Example** 1241 1242```ts 1243import { BusinessError } from '@kit.BasicServicesKit'; 1244 1245dataPreferences.get('startup', 'default', (err: BusinessError, val: preferences.ValueType) => { 1246 if (err) { 1247 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1248 return; 1249 } 1250 console.info("Obtained the value of 'startup' successfully. val: " + val); 1251}) 1252``` 1253 1254### get 1255 1256get(key: string, defValue: ValueType): Promise<ValueType> 1257 1258Obtains 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. 1259 1260**Atomic service API**: This API can be used in atomic services since API version 11. 1261 1262**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1263 1264 **Parameters** 1265 1266| Name | Type | Mandatory| Description | 1267| -------- | ----------------------- | ---- |--------| 1268| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1269| defValue | [ValueType](#valuetype) | Yes | Default value to be returned.| 1270 1271**Return value** 1272 1273| Type | Description | 1274| ----------------------------------- | ----------------------------- | 1275| Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| 1276 1277**Error codes** 1278 1279For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1280 1281| ID| Error Message | 1282| -------- | ------------------------------ | 1283| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1284| 15500000 | Inner error. | 1285 1286**Example** 1287 1288```ts 1289import { BusinessError } from '@kit.BasicServicesKit'; 1290 1291let promise = dataPreferences.get('startup', 'default'); 1292promise.then((data: preferences.ValueType) => { 1293 console.info("Got the value of 'startup'. Data: " + data); 1294}).catch((err: BusinessError) => { 1295 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1296}) 1297``` 1298 1299### getSync<sup>10+</sup> 1300 1301getSync(key: string, defValue: ValueType): ValueType 1302 1303Obtains 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. 1304 1305**Atomic service API**: This API can be used in atomic services since API version 11. 1306 1307**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1308 1309**Parameters** 1310 1311| Name | Type | Mandatory| Description | 1312| -------- | ----------------------- | ---- |---------------------| 1313| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1314| defValue | [ValueType](#valuetype) | Yes | Default value to be returned.| 1315 1316**Return value** 1317 1318| Type | Description | 1319| ----------------------------------- | ----------------------------- | 1320| [ValueType](#valuetype) | Returns the value obtained.| 1321 1322**Error codes** 1323 1324For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1325 1326| ID| Error Message | 1327| -------- | ------------------------------ | 1328| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1329| 15500000 | Inner error. | 1330 1331**Example** 1332 1333```ts 1334let value: preferences.ValueType = dataPreferences.getSync('startup', 'default'); 1335``` 1336 1337### getAll 1338 1339getAll(callback: AsyncCallback<Object>): void 1340 1341Obtains all KV pairs from this **Preferences** instance. This API uses an asynchronous callback to return the result. 1342 1343**Atomic service API**: This API can be used in atomic services since API version 11. 1344 1345**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1346 1347**Parameters** 1348 1349| Name | Type | Mandatory| Description | 1350| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1351| 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.| 1352 1353**Error codes** 1354 1355For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1356 1357| ID| Error Message | 1358| -------- | ------------------------------ | 1359| 401 | Parameter error. Mandatory parameters are left unspecified.| 1360| 15500000 | Inner error. | 1361 1362**Example** 1363 1364```ts 1365import { BusinessError } from '@kit.BasicServicesKit'; 1366 1367// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1368// 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. 1369function getObjKeys(obj: Object): string[] { 1370 let keys = Object.keys(obj); 1371 return keys; 1372} 1373 1374dataPreferences.getAll((err: BusinessError, value: Object) => { 1375 if (err) { 1376 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1377 return; 1378 } 1379 let allKeys = getObjKeys(value); 1380 console.info("getAll keys = " + allKeys); 1381 console.info("getAll object = " + JSON.stringify(value)); 1382}) 1383``` 1384 1385 1386### getAll 1387 1388getAll(): Promise<Object> 1389 1390Obtains all KV pairs from this **Preferences** instance. This API uses a promise to return the result. 1391 1392**Atomic service API**: This API can be used in atomic services since API version 11. 1393 1394**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1395 1396**Return value** 1397 1398| Type | Description | 1399| --------------------- | ------------------------------------------- | 1400| Promise<Object> | Promise used to return the KV pairs obtained.| 1401 1402**Error codes** 1403 1404For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 1405 1406| ID| Error Message | 1407| -------- | ------------------------------ | 1408| 15500000 | Inner error. | 1409 1410**Example** 1411 1412```ts 1413import { BusinessError } from '@kit.BasicServicesKit'; 1414 1415// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1416// 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. 1417function getObjKeys(obj: Object): string[] { 1418 let keys = Object.keys(obj); 1419 return keys; 1420} 1421 1422let promise = dataPreferences.getAll(); 1423promise.then((value: Object) => { 1424 let allKeys = getObjKeys(value); 1425 console.info('getAll keys = ' + allKeys); 1426 console.info("getAll object = " + JSON.stringify(value)); 1427}).catch((err: BusinessError) => { 1428 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1429}) 1430``` 1431 1432### getAllSync<sup>10+</sup> 1433 1434getAllSync(): Object 1435 1436Obtains all KV pairs from this **Preferences** instance. This API returns the result synchronously. 1437 1438**Atomic service API**: This API can be used in atomic services since API version 11. 1439 1440**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1441 1442**Return value** 1443 1444| Type | Description | 1445| --------------------- | ------------------------------------------- | 1446| Object | Returns all KV pairs obtained.| 1447 1448**Error codes** 1449 1450For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 1451 1452| ID| Error Message | 1453| -------- | ------------------------------ | 1454| 15500000 | Inner error. | 1455 1456**Example** 1457 1458```ts 1459// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1460// 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. 1461function getObjKeys(obj: Object): string[] { 1462 let keys = Object.keys(obj); 1463 return keys; 1464} 1465 1466let value = dataPreferences.getAllSync(); 1467let allKeys = getObjKeys(value); 1468console.info('getAll keys = ' + allKeys); 1469console.info("getAll object = " + JSON.stringify(value)); 1470``` 1471 1472### put 1473 1474put(key: string, value: ValueType, callback: AsyncCallback<void>): void 1475 1476Writes 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. 1477 1478 > **NOTE** 1479 > 1480 > If the value contains a string that is not in UTF-8 format, store it in a Uint8Array. Otherwise, the persistent file may be damaged due to format errors. 1481 > 1482 > If the key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists. 1483 1484**Atomic service API**: This API can be used in atomic services since API version 11. 1485 1486**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1487 1488**Parameters** 1489 1490| Name | Type | Mandatory| Description | 1491| -------- | ------------------------- | ---- |-------------------------| 1492| key | string | Yes | Key of the data. It cannot be empty.| 1493| value | [ValueType](#valuetype) | Yes | Value to write.| 1494| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1495 1496**Error codes** 1497 1498For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1499 1500| ID| Error Message | 1501| -------- | ------------------------------ | 1502| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1503| 15500000 | Inner error. | 1504 1505**Example** 1506 1507```ts 1508import { BusinessError } from '@kit.BasicServicesKit'; 1509 1510dataPreferences.put('startup', 'auto', (err: BusinessError) => { 1511 if (err) { 1512 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1513 return; 1514 } 1515 console.info("Successfully put the value of 'startup'."); 1516}) 1517``` 1518 1519 1520### put 1521 1522put(key: string, value: ValueType): Promise<void> 1523 1524Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 1525 1526 > **NOTE** 1527 > 1528 > If the value contains a string that is not in UTF-8 format, store it in a Uint8Array. Otherwise, the persistent file may be damaged due to format errors. 1529 > 1530 > If the key already exists, **put()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists. 1531 1532**Atomic service API**: This API can be used in atomic services since API version 11. 1533 1534**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1535 1536**Parameters** 1537 1538| Name| Type | Mandatory| Description | 1539| ------ | ----------------------- | ---- |--------------------------| 1540| key | string | Yes | Key of the data. It cannot be empty. | 1541| value | [ValueType](#valuetype) | Yes | Value to write.| 1542 1543**Return value** 1544 1545| Type | Description | 1546| ------------------- | ------------------------- | 1547| Promise<void> | Promise that returns no value.| 1548 1549**Error codes** 1550 1551For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1552 1553| ID| Error Message | 1554| -------- | ------------------------------ | 1555| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1556| 15500000 | Inner error. | 1557 1558**Example** 1559 1560```ts 1561import { BusinessError } from '@kit.BasicServicesKit'; 1562 1563let promise = dataPreferences.put('startup', 'auto'); 1564promise.then(() => { 1565 console.info("Successfully put the value of 'startup'."); 1566}).catch((err: BusinessError) => { 1567 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1568}) 1569``` 1570 1571 1572### putSync<sup>10+</sup> 1573 1574putSync(key: string, value: ValueType): void 1575 1576Writes data to this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 1577 1578 > **NOTE** 1579 > 1580 > If the value contains a string that is not in UTF-8 format, store it in a Uint8Array. Otherwise, the persistent file may be damaged due to format errors. 1581 > 1582 > If the key already exists, **putSync()** overwrites the value. You can use **hasSync()** to check whether the KV pair exists. 1583 1584**Atomic service API**: This API can be used in atomic services since API version 11. 1585 1586**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1587 1588**Parameters** 1589 1590| Name| Type | Mandatory| Description | 1591| ------ | ----------------------- | ---- | ------------------------ | 1592| key | string | Yes | Key of the data. It cannot be empty.| 1593| value | [ValueType](#valuetype) | Yes | Value to write.| 1594 1595**Error codes** 1596 1597For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1598 1599| ID| Error Message | 1600| -------- | ------------------------------ | 1601| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1602| 15500000 | Inner error. | 1603 1604**Example** 1605 1606```ts 1607dataPreferences.putSync('startup', 'auto'); 1608``` 1609 1610 1611### has 1612 1613has(key: string, callback: AsyncCallback<boolean>): void 1614 1615Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses an asynchronous callback to return the result. 1616 1617**Atomic service API**: This API can be used in atomic services since API version 11. 1618 1619**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1620 1621**Parameters** 1622 1623| Name | Type | Mandatory| Description | 1624| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | 1625| key | string | Yes | Key of the data to check. It cannot be empty. | 1626| 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.| 1627 1628**Error codes** 1629 1630For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1631 1632| ID| Error Message | 1633| -------- | ------------------------------ | 1634| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1635| 15500000 | Inner error. | 1636 1637**Example** 1638 1639```ts 1640import { BusinessError } from '@kit.BasicServicesKit'; 1641 1642dataPreferences.has('startup', (err: BusinessError, val: boolean) => { 1643 if (err) { 1644 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1645 return; 1646 } 1647 if (val) { 1648 console.info("The key 'startup' is contained."); 1649 } else { 1650 console.info("The key 'startup' is not contained."); 1651 } 1652}) 1653``` 1654 1655 1656### has 1657 1658has(key: string): Promise<boolean> 1659 1660Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result. 1661 1662**Atomic service API**: This API can be used in atomic services since API version 11. 1663 1664**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1665 1666**Parameters** 1667 1668| Name| Type | Mandatory| Description | 1669| ------ | ------ | ---- | ------------------------------- | 1670| key | string | Yes | Key of the data to check. It cannot be empty.| 1671 1672**Return value** 1673 1674| Type | Description | 1675| ---------------------- | ------------------------------------------------------------ | 1676| 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.| 1677 1678**Error codes** 1679 1680For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1681 1682| ID| Error Message | 1683| -------- | ------------------------------ | 1684| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1685| 15500000 | Inner error. | 1686 1687**Example** 1688 1689```ts 1690import { BusinessError } from '@kit.BasicServicesKit'; 1691 1692let promise = dataPreferences.has('startup'); 1693promise.then((val: boolean) => { 1694 if (val) { 1695 console.info("The key 'startup' is contained."); 1696 } else { 1697 console.info("The key 'startup' is not contained."); 1698 } 1699}).catch((err: BusinessError) => { 1700 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1701}) 1702``` 1703 1704 1705### hasSync<sup>10+</sup> 1706 1707hasSync(key: string): boolean 1708 1709Checks whether this **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously. 1710 1711**Atomic service API**: This API can be used in atomic services since API version 11. 1712 1713**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1714 1715**Parameters** 1716 1717| Name| Type | Mandatory| Description | 1718| ------ | ------ | ---- | ------------------------------- | 1719| key | string | Yes | Key of the data to check. It cannot be empty.| 1720 1721**Return value** 1722 1723| Type | Description | 1724| ---------------------- | ------------------------------------------------------------ | 1725| boolean | If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| 1726 1727**Error codes** 1728 1729For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1730 1731| ID| Error Message | 1732| -------- | ------------------------------ | 1733| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1734| 15500000 | Inner error. | 1735 1736**Example** 1737 1738```ts 1739let isExist: boolean = dataPreferences.hasSync('startup'); 1740if (isExist) { 1741 console.info("The key 'startup' is contained."); 1742} else { 1743 console.info("The key 'startup' is not contained."); 1744} 1745``` 1746 1747 1748### delete 1749 1750delete(key: string, callback: AsyncCallback<void>): void 1751 1752Deletes 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. 1753 1754**Atomic service API**: This API can be used in atomic services since API version 11. 1755 1756**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1757 1758**Parameters** 1759 1760| Name | Type | Mandatory| Description | 1761| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1762| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | 1763| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1764 1765**Error codes** 1766 1767For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1768 1769| ID| Error Message | 1770| -------- | ------------------------------ | 1771| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1772| 15500000 | Inner error. | 1773 1774**Example** 1775 1776```ts 1777import { BusinessError } from '@kit.BasicServicesKit'; 1778 1779dataPreferences.delete('startup', (err: BusinessError) => { 1780 if (err) { 1781 console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); 1782 return; 1783 } 1784 console.info("Deleted the key 'startup'."); 1785}) 1786``` 1787 1788 1789### delete 1790 1791delete(key: string): Promise<void> 1792 1793Deletes 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. 1794 1795**Atomic service API**: This API can be used in atomic services since API version 11. 1796 1797**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1798 1799**Parameters** 1800 1801| Name| Type | Mandatory| Description | 1802| ------ | ------ | ---- | ------------------------------- | 1803| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 1804 1805**Return value** 1806 1807| Type | Description | 1808| ------------------- | ------------------------- | 1809| Promise<void> | Promise that returns no value.| 1810 1811**Error codes** 1812 1813For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1814 1815| ID| Error Message | 1816| -------- | ------------------------------ | 1817| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1818| 15500000 | Inner error. | 1819 1820**Example** 1821 1822```ts 1823import { BusinessError } from '@kit.BasicServicesKit'; 1824 1825let promise = dataPreferences.delete('startup'); 1826promise.then(() => { 1827 console.info("Deleted the key 'startup'."); 1828}).catch((err: BusinessError) => { 1829 console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); 1830}) 1831``` 1832 1833 1834### deleteSync<sup>10+</sup> 1835 1836deleteSync(key: string): void 1837 1838Deletes a KV pair from this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 1839 1840**Atomic service API**: This API can be used in atomic services since API version 11. 1841 1842**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1843 1844**Parameters** 1845 1846| Name| Type | Mandatory| Description | 1847| ------ | ------ | ---- | ------------------------------- | 1848| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 1849 1850**Error codes** 1851 1852For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 1853 1854| ID| Error Message | 1855| -------- | ------------------------------ | 1856| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 1857| 15500000 | Inner error. | 1858 1859**Example** 1860 1861```ts 1862dataPreferences.deleteSync('startup'); 1863``` 1864 1865 1866### flush 1867 1868flush(callback: AsyncCallback<void>): void 1869 1870Flushes the data in this **Preferences** instance to the persistent file. This API uses an asynchronous callback to return the result. 1871 1872 > **NOTE** 1873 > 1874 > If no data is modified or the modified data is the same as the cached data, the persistent file will not be updated. 1875 > 1876 > This API is exclusively applicable to the XML storage and does not require invocation in the GSKV storage. When GSKV mode is selected, data operations via preferences are flushed to disk in real-time. For details about the preferences storage types, see [Storage Types](../../database/data-persistence-by-preferences.md#storage-types). 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 > This API is exclusively applicable to the XML storage and does not require invocation in the GSKV storage. When GSKV mode is selected, data operations via preferences are flushed to disk in real-time. For details about the preferences storage types, see [Storage Types](../../database/data-persistence-by-preferences.md#storage-types). 1923 1924**Atomic service API**: This API can be used in atomic services since API version 11. 1925 1926**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1927 1928**Return value** 1929 1930| Type | Description | 1931| ------------------- | ------------------------- | 1932| Promise<void> | Promise that returns no value.| 1933 1934**Error codes** 1935 1936For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 1937 1938| ID| Error Message | 1939| -------- | ------------------------------ | 1940| 15500000 | Inner error. | 1941 1942**Example** 1943 1944```ts 1945import { BusinessError } from '@kit.BasicServicesKit'; 1946 1947let promise = dataPreferences.flush(); 1948promise.then(() => { 1949 console.info("Successfully flushed data."); 1950}).catch((err: BusinessError) => { 1951 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1952}) 1953``` 1954 1955### flushSync<sup>14+</sup> 1956 1957flushSync(): void 1958 1959Flushes the data in the cached **Preferences** instance to the persistent file. 1960 1961 > **NOTE** 1962 > 1963 > If no data is modified or the modified data is the same as the cached data, the persistent file will not be updated. 1964 1965**Atomic service API**: This API can be used in atomic services since API version 14. 1966 1967**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1968 1969**Error codes** 1970 1971For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 1972 1973| ID| Error Message | 1974| -------- | ------------------------------ | 1975| 15500000 | Inner error. | 1976 1977**Example** 1978 1979```ts 1980dataPreferences.flushSync(); 1981``` 1982 1983### clear 1984 1985clear(callback: AsyncCallback<void>): void 1986 1987Clears this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 1988 1989**Atomic service API**: This API can be used in atomic services since API version 11. 1990 1991**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1992 1993**Parameters** 1994 1995| Name | Type | Mandatory| Description | 1996| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1997| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1998 1999**Error codes** 2000 2001For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2002 2003| ID| Error Message | 2004| -------- | ------------------------------ | 2005| 401 | Parameter error. Mandatory parameters are left unspecified. | 2006| 15500000 | Inner error. | 2007 2008**Example** 2009 2010```ts 2011import { BusinessError } from '@kit.BasicServicesKit'; 2012 2013dataPreferences.clear((err: BusinessError) =>{ 2014 if (err) { 2015 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 2016 return; 2017 } 2018 console.info("Successfully cleared data."); 2019}) 2020``` 2021 2022 2023### clear 2024 2025clear(): Promise<void> 2026 2027Clears this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 2028 2029**Atomic service API**: This API can be used in atomic services since API version 11. 2030 2031**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2032 2033**Return value** 2034 2035| Type | Description | 2036| ------------------- | ------------------------- | 2037| Promise<void> | Promise that returns no value.| 2038 2039**Error codes** 2040 2041For details about the error codes, see [User Preference Error Codes](errorcode-preferences.md). 2042 2043| ID| Error Message | 2044| -------- | ------------------------------ | 2045| 15500000 | Inner error. | 2046 2047**Example** 2048 2049```ts 2050import { BusinessError } from '@kit.BasicServicesKit'; 2051 2052let promise = dataPreferences.clear(); 2053promise.then(() => { 2054 console.info("Successfully cleared data."); 2055}).catch((err: BusinessError) => { 2056 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 2057}) 2058``` 2059 2060 2061### clearSync<sup>10+</sup> 2062 2063clearSync(): void 2064 2065Clears this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 2066 2067**Atomic service API**: This API can be used in atomic services since API version 11. 2068 2069**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2070 2071**Example** 2072 2073```ts 2074dataPreferences.clearSync(); 2075``` 2076 2077 2078### on('change') 2079 2080on(type: 'change', callback: Callback<string>): void 2081 2082Subscribes to data changes. The registered callback will be invoked to return the new value if the data change is [flushed](#flush). 2083 2084 > **NOTE** 2085 > 2086 > 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. 2087 2088**Atomic service API**: This API can be used in atomic services since API version 11. 2089 2090**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2091 2092**Parameters** 2093 2094| Name | Type | Mandatory| Description | 2095| -------- | -------- | ---- | ---------------------------------------- | 2096| type | string | Yes | Event type. The value is **'change'**, which indicates data changes.| 2097| callback | Callback<string> | Yes | Callback used to return the data change. | 2098 2099**Error codes** 2100 2101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2102 2103| ID| Error Message | 2104| -------- | ------------------------------ | 2105| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2106| 15500000 | Inner error. | 2107 2108**Example** 2109 2110```ts 2111import { BusinessError } from '@kit.BasicServicesKit'; 2112 2113let observer = (key: string) => { 2114 console.info("The key " + key + " changed."); 2115} 2116dataPreferences.on('change', observer); 2117dataPreferences.putSync('startup', 'manual'); 2118dataPreferences.flush((err: BusinessError) => { 2119 if (err) { 2120 console.error("Failed to flush. Cause: " + err); 2121 return; 2122 } 2123 console.info("Successfully flushed data."); 2124}) 2125``` 2126 2127### on('multiProcessChange')<sup>10+</sup> 2128 2129on(type: 'multiProcessChange', callback: Callback<string>): void 2130 2131Subscribes to data changes between processes. 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. 2132 2133This 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. 2134 2135 > **NOTE** 2136 > 2137 > 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. 2138 > 2139 > 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. 2140 2141**Atomic service API**: This API can be used in atomic services since API version 11. 2142 2143**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2144 2145**Parameters** 2146 2147| Name | Type | Mandatory| Description | 2148| -------- | -------- | ---- | ------------------------------------------------------------ | 2149| type | string | Yes | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.| 2150| callback | Callback<string> | Yes | Callback used to return the data change. | 2151 2152**Error codes** 2153 2154For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2155 2156| ID| Error Message | 2157| -------- | -------------------------------------- | 2158| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2159| 15500000 | Inner error. | 2160| 15500019 | Failed to obtain the subscription service. | 2161 2162**Example** 2163 2164```ts 2165import { BusinessError } from '@kit.BasicServicesKit'; 2166 2167let observer = (key: string) => { 2168 console.info("The key " + key + " changed."); 2169} 2170dataPreferences.on('multiProcessChange', observer); 2171dataPreferences.putSync('startup', 'manual'); 2172dataPreferences.flush((err: BusinessError) => { 2173 if (err) { 2174 console.error("Failed to flush. Cause: " + err); 2175 return; 2176 } 2177 console.info("Successfully flushed data."); 2178}) 2179``` 2180 2181### on('dataChange')<sup>12+</sup> 2182 2183on(type: 'dataChange', keys: Array<string>, callback: Callback<Record<string, ValueType>>): void 2184 2185Subscribes to changes of specific data. The registered callback will be invoked only after the values of the specified keys are changed and [flushed](#flush). 2186 2187 > **NOTE** 2188 > 2189 > 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. 2190 2191**Atomic service API**: This API can be used in atomic services since API version 12. 2192 2193**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2194 2195**Parameters** 2196 2197| Name | Type | Mandatory| Description | 2198| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2199| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | 2200| keys | Array<string> | Yes | Array of the keys to be observed. | 2201| 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.| 2202 2203**Error codes** 2204 2205For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2206 2207| ID| Error Message | 2208| -------- | ------------------------------ | 2209| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2210| 15500000 | Inner error. | 2211 2212**Example** 2213 2214```ts 2215import { BusinessError } from '@kit.BasicServicesKit'; 2216 2217let observer = (data: Record<string, preferences.ValueType>) => { 2218 for (const keyValue of Object.entries(data)) { 2219 console.info(`observer : ${keyValue}`); 2220 } 2221 console.info("The observer called."); 2222} 2223let keys = ['name', 'age']; 2224dataPreferences.on('dataChange', keys, observer); 2225dataPreferences.putSync('name', 'xiaohong'); 2226dataPreferences.putSync('weight', 125); 2227dataPreferences.flush((err: BusinessError) => { 2228 if (err) { 2229 console.error("Failed to flush. Cause: " + err); 2230 return; 2231 } 2232 console.info("Successfully flushed data."); 2233}) 2234``` 2235 2236### off('change') 2237 2238off(type: 'change', callback?: Callback<string>): void 2239 2240Unsubscribes from data changes. 2241 2242**Atomic service API**: This API can be used in atomic services since API version 11. 2243 2244**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2245 2246**Parameters** 2247 2248| Name | Type | Mandatory| Description | 2249| -------- | -------- | ---- | ------------------------------------------------------------ | 2250| type | string | Yes | Event type. The value is **'change'**, which indicates data changes. | 2251| callback | Callback<string> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.| 2252 2253**Error codes** 2254 2255For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2256 2257| ID| Error Message | 2258| -------- | ------------------------------ | 2259| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2260| 15500000 | Inner error. | 2261 2262**Example** 2263 2264```ts 2265import { BusinessError } from '@kit.BasicServicesKit'; 2266 2267let observer = (key: string) => { 2268 console.info("The key " + key + " changed."); 2269} 2270dataPreferences.on('change', observer); 2271dataPreferences.putSync('startup', 'auto'); 2272dataPreferences.flush((err: BusinessError) => { 2273 if (err) { 2274 console.error("Failed to flush. Cause: " + err); 2275 return; 2276 } 2277 console.info("Successfully flushed data."); 2278}) 2279dataPreferences.off('change', observer); 2280``` 2281 2282### off('multiProcessChange')<sup>10+</sup> 2283 2284off(type: 'multiProcessChange', callback?: Callback<string>): void 2285 2286Unsubscribes from inter-process data changes. 2287 2288This 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. 2289 2290**Atomic service API**: This API can be used in atomic services since API version 11. 2291 2292**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2293 2294**Parameters** 2295 2296| Name | Type | Mandatory| Description | 2297| -------- | -------- | ---- | ------------------------------------------------------------ | 2298| type | string | Yes | Event type. The value is **'multiProcessChange'**, which indicates inter-process data changes.| 2299| callback | Callback<string> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.| 2300 2301**Error codes** 2302 2303For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2304 2305| ID| Error Message | 2306| -------- | ------------------------------ | 2307| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2308| 15500000 | Inner error. | 2309 2310**Example** 2311 2312```ts 2313import { BusinessError } from '@kit.BasicServicesKit'; 2314 2315let observer = (key: string) => { 2316 console.info("The key " + key + " changed."); 2317} 2318dataPreferences.on('multiProcessChange', observer); 2319dataPreferences.putSync('startup', 'auto'); 2320dataPreferences.flush((err: BusinessError) => { 2321 if (err) { 2322 console.error("Failed to flush. Cause: " + err); 2323 return; 2324 } 2325 console.info("Successfully flushed data."); 2326}) 2327dataPreferences.off('multiProcessChange', observer); 2328``` 2329### off('dataChange')<sup>12+</sup> 2330 2331off(type: 'dataChange', keys: Array<string>, callback?: Callback<Record<string, ValueType>>): void 2332 2333Unsubscribes from changes of specific data. 2334 2335**Atomic service API**: This API can be used in atomic services since API version 12. 2336 2337**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2338 2339**Parameters** 2340 2341| Name | Type | Mandatory| Description | 2342| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2343| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | 2344| keys | Array<string> | Yes | Array of keys to be unsubscribed from. If this parameter is left empty, all keys are unsubscribed from.| 2345| 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.| 2346 2347**Error codes** 2348 2349For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). 2350 2351| ID| Error Message | 2352| -------- | ------------------------------ | 2353| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | 2354| 15500000 | Inner error. | 2355 2356**Example** 2357 2358```ts 2359import { BusinessError } from '@kit.BasicServicesKit'; 2360 2361let observer = (data: Record<string, preferences.ValueType>) => { 2362 for (const keyValue of Object.entries(data)) { 2363 console.info(`observer : ${keyValue}`); 2364 } 2365 console.info("The observer called."); 2366} 2367let keys = ['name', 'age']; 2368dataPreferences.on('dataChange', keys, observer); 2369dataPreferences.putSync('name', 'xiaohong'); 2370dataPreferences.putSync('weight', 125); 2371dataPreferences.flush((err: BusinessError) => { 2372 if (err) { 2373 console.error("Failed to flush. Cause: " + err); 2374 return; 2375 } 2376 console.info("Successfully flushed data."); 2377}) 2378dataPreferences.off('dataChange', keys, observer); 2379``` 2380 2381## ValueType 2382 2383type ValueType = number | string | boolean | Array\<number> | Array\<string> | Array\<boolean> | Uint8Array | object | bigint 2384 2385Enumerates the value types. 2386 2387**Atomic service API**: This API can be used in atomic services since API version 11. 2388 2389**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 2390 2391| Type | Description | 2392|--------------------------|-------------------| 2393| number | The value is a number. | 2394| string | The value is a string. | 2395| boolean | The value is true or false. | 2396| Array\<number> | The value is an array of numbers. | 2397| Array\<boolean> | The value is a Boolean array. | 2398| Array\<string> | The value is an array of strings. | 2399| Uint8Array<sup>11+</sup> | The value is an array of 8-bit unsigned integers.| 2400| object<sup>12+</sup> | The value is an object.| 2401| bigint<sup>12+</sup> | The value is an integer in any format. | 2402