1# @ohos.data.preferences (User Preferences) 2 3The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs, including querying, modifying, and persisting KV pairs. 4 5The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. 6 7 8> **NOTE** 9> 10> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 11 12 13## Modules to Import 14 15```ts 16import dataPreferences from '@ohos.data.preferences'; 17``` 18 19## Constants 20 21**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 22 23| Name | Type| Readable| Writable| Description | 24| ---------------- | -------- | ---- | ---- | --------------------------------------- | 25| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. | 26| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.| 27 28 29## dataPreferences.getPreferences 30 31getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void 32 33Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. 34 35**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 36 37**Parameters** 38 39| Name | Type | Mandatory| Description | 40| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | 41| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 42| name | string | Yes | Name of the **Preferences** instance. | 43| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked 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.| 44 45**Example** 46 47FA model: 48 49```ts 50import featureAbility from '@ohos.ability.featureAbility'; 51import { BusinessError } from '@ohos.base'; 52 53let context = featureAbility.getContext(); 54let preferences: dataPreferences.Preferences | null = null; 55 56dataPreferences.getPreferences(context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => { 57 if (err) { 58 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 59 return; 60 } 61 preferences = val; 62 console.info("Succeeded in getting preferences."); 63}) 64``` 65 66Stage model: 67 68```ts 69import UIAbility from '@ohos.app.ability.UIAbility'; 70import { BusinessError } from '@ohos.base'; 71import window from '@ohos.window'; 72 73let preferences: dataPreferences.Preferences | null = null; 74 75class EntryAbility extends UIAbility { 76 onWindowStageCreate(windowStage: window.WindowStage) { 77 dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => { 78 if (err) { 79 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 80 return; 81 } 82 preferences = val; 83 console.info("Succeeded in getting preferences."); 84 }) 85 } 86} 87``` 88 89## dataPreferences.getPreferences 90 91getPreferences(context: Context, name: string): Promise<Preferences> 92 93Obtains a **Preferences** instance. This API uses a promise to return the result. 94 95**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 96 97**Parameters** 98 99| Name | Type | Mandatory| Description | 100| ------- | ------------------------------------- | ---- | ----------------------- | 101| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 102| name | string | Yes | Name of the **Preferences** instance.| 103 104**Return value** 105 106| Type | Description | 107| ------------------------------------------ | ---------------------------------- | 108| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| 109 110**Example** 111 112FA model: 113 114```ts 115// Obtain the context. 116import featureAbility from '@ohos.ability.featureAbility'; 117import { BusinessError } from '@ohos.base' 118 119let context = featureAbility.getContext(); 120 121let preferences: dataPreferences.Preferences | null = null; 122let promise = dataPreferences.getPreferences(context, 'myStore'); 123promise.then((object: dataPreferences.Preferences) => { 124 preferences = object; 125 console.info("Succeeded in getting preferences."); 126}).catch((err: BusinessError) => { 127 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 128}) 129``` 130 131Stage model: 132 133```ts 134import UIAbility from '@ohos.app.ability.UIAbility'; 135import { BusinessError } from '@ohos.base' 136import window from '@ohos.window'; 137 138let preferences: dataPreferences.Preferences | null = null; 139 140class EntryAbility extends UIAbility { 141 onWindowStageCreate(windowStage: window.WindowStage) { 142 let promise = dataPreferences.getPreferences(this.context, 'myStore'); 143 promise.then((object: dataPreferences.Preferences) => { 144 preferences = object; 145 console.info("Succeeded in getting preferences."); 146 }).catch((err: BusinessError) => { 147 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 148 }) 149 } 150} 151``` 152 153## dataPreferences.getPreferences<sup>10+</sup> 154 155getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void 156 157Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. 158 159**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 160 161**Parameters** 162 163| Name | Type | Mandatory| Description | 164| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 165| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 166| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 167| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked 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. | 168 169**Error codes** 170 171For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 172 173| ID| Error Message | 174| -------- | ------------------------------ | 175| 15501001 | Only supported in stage mode. | 176| 15501002 | The data group id is not valid. | 177 178**Example** 179 180FA model: 181 182```ts 183// Obtain the context. 184import featureAbility from '@ohos.ability.featureAbility'; 185import { BusinessError } from '@ohos.base' 186 187let context = featureAbility.getContext(); 188let preferences: dataPreferences.Preferences | null = null; 189 190let options: dataPreferences.Options = { name: 'myStore' }; 191dataPreferences.getPreferences(context, options, (err: BusinessError, val: dataPreferences.Preferences) => { 192 if (err) { 193 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 194 return; 195 } 196 preferences = val; 197 console.info("Succeeded in getting preferences."); 198}) 199``` 200 201 202Stage model: 203 204```ts 205import UIAbility from '@ohos.app.ability.UIAbility'; 206import { BusinessError } from '@ohos.base' 207import window from '@ohos.window'; 208 209let preferences: dataPreferences.Preferences | null = null; 210 211class EntryAbility extends UIAbility { 212 onWindowStageCreate(windowStage: window.WindowStage) { 213 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 214 dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => { 215 if (err) { 216 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 217 return; 218 } 219 preferences = val; 220 console.info("Succeeded in getting preferences."); 221 }) 222 } 223} 224``` 225 226## dataPreferences.getPreferences<sup>10+</sup> 227 228getPreferences(context: Context, options: Options): Promise<Preferences> 229 230Obtains a **Preferences** instance. This API uses a promise to return the result. 231 232**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 233 234**Parameters** 235 236| Name | Type | Mandatory| Description | 237| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 238| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 239| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 240 241**Return value** 242 243| Type | Description | 244| --------------------------------------- | ---------------------------------- | 245| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| 246 247**Error codes** 248 249For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 250 251| ID| Error Message | 252| -------- | ------------------------------ | 253| 15501001 | Only supported in stage mode. | 254| 15501002 | The data group id is not valid. | 255 256**Example** 257 258FA model: 259 260```ts 261// Obtain the context. 262import featureAbility from '@ohos.ability.featureAbility'; 263import { BusinessError } from '@ohos.base' 264 265let context = featureAbility.getContext(); 266 267let preferences: dataPreferences.Preferences | null = null; 268let options: dataPreferences.Options = { name: 'myStore' }; 269let promise = dataPreferences.getPreferences(context, options); 270promise.then((object: dataPreferences.Preferences) => { 271 preferences = object; 272 console.info("Succeeded in getting preferences."); 273}).catch((err: BusinessError) => { 274 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 275}) 276``` 277 278Stage model: 279 280```ts 281import UIAbility from '@ohos.app.ability.UIAbility'; 282import { BusinessError } from '@ohos.base' 283import window from '@ohos.window'; 284 285let preferences: dataPreferences.Preferences | null = null; 286 287class EntryAbility extends UIAbility { 288 onWindowStageCreate(windowStage: window.WindowStage) { 289 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 290 let promise = dataPreferences.getPreferences(this.context, options); 291 promise.then((object: dataPreferences.Preferences) => { 292 preferences = object; 293 console.info("Succeeded in getting preferences."); 294 }).catch((err: BusinessError) => { 295 console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); 296 }) 297 } 298} 299``` 300 301## dataPreferences.getPreferencesSync<sup>10+</sup> 302 303getPreferencesSync(context: Context, options: Options): Preferences 304 305Obtains a **Preferences** instance. This API returns the result synchronously. 306 307**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 308 309**Parameters** 310 311| Name | Type | Mandatory| Description | 312| ------- | --------------------- | ---- | ------------------------------------------------------------ | 313| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 314| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 315 316**Return value** 317 318| Type | Description | 319| --------------------------- | --------------------- | 320| [Preferences](#preferences) | **Preferences** instance obtained.| 321 322**Error codes** 323 324For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 325 326| ID| Error Message | 327| -------- | ------------------------------- | 328| 15501001 | Only supported in stage mode. | 329| 15501002 | The data group id is not valid. | 330 331**Example** 332 333FA model: 334 335```ts 336// Obtain the context. 337import featureAbility from '@ohos.ability.featureAbility'; 338 339let context = featureAbility.getContext(); 340let preferences: dataPreferences.Preferences | null = null; 341 342let options: dataPreferences.Options = { name: 'myStore' }; 343preferences = dataPreferences.getPreferencesSync(context, options); 344``` 345 346Stage model: 347 348```ts 349import UIAbility from '@ohos.app.ability.UIAbility'; 350import window from '@ohos.window'; 351 352let preferences: dataPreferences.Preferences | null = null; 353 354class EntryAbility extends UIAbility { 355 onWindowStageCreate(windowStage: window.WindowStage) { 356 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 357 preferences = dataPreferences.getPreferencesSync(this.context, options); 358 } 359} 360``` 361 362## dataPreferences.deletePreferences 363 364deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void 365 366Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result. 367 368After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. 369 370**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 371 372**Parameters** 373 374| Name | Type | Mandatory| Description | 375| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | 376| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 377| name | string | Yes | Name of the **Preferences** instance. | 378| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 379 380**Error codes** 381 382For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 383 384| ID| Error Message | 385| -------- | ------------------------------| 386| 15500010 | Failed to delete preferences file. | 387 388**Example** 389 390FA model: 391 392```ts 393// Obtain the context. 394import featureAbility from '@ohos.ability.featureAbility'; 395import { BusinessError } from '@ohos.base' 396 397let context = featureAbility.getContext(); 398 399dataPreferences.deletePreferences(context, 'myStore', (err: BusinessError) => { 400 if (err) { 401 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 402 return; 403 } 404 console.info("Succeeded in deleting preferences."); 405}) 406``` 407 408Stage model: 409 410```ts 411import UIAbility from '@ohos.app.ability.UIAbility'; 412import { BusinessError } from '@ohos.base' 413import window from '@ohos.window'; 414 415class EntryAbility extends UIAbility { 416 onWindowStageCreate(windowStage: window.WindowStage) { 417 dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { 418 if (err) { 419 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 420 return; 421 } 422 console.info("Succeeded in deleting preferences."); 423 }) 424 } 425} 426``` 427 428## dataPreferences.deletePreferences 429 430deletePreferences(context: Context, name: string): Promise<void> 431 432Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result. 433 434After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. 435 436**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 437 438**Parameters** 439 440| Name | Type | Mandatory| Description | 441| ------- | ------------------------------------- | ---- | ----------------------- | 442| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 443| name | string | Yes | Name of the **Preferences** instance.| 444 445**Return value** 446 447| Type | Description | 448| ------------------- | ------------------------- | 449| Promise<void> | Promise that returns no value.| 450 451**Error codes** 452 453For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 454 455| ID| Error Message | 456| -------- | ------------------------------| 457| 15500010 | Failed to delete preferences file. | 458 459**Example** 460 461FA model: 462 463```ts 464// Obtain the context. 465import featureAbility from '@ohos.ability.featureAbility'; 466import { BusinessError } from '@ohos.base' 467 468let context = featureAbility.getContext(); 469 470let promise = dataPreferences.deletePreferences(context, 'myStore'); 471promise.then(() => { 472 console.info("Succeeded in deleting preferences."); 473}).catch((err: BusinessError) => { 474 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 475}) 476``` 477 478Stage model: 479 480```ts 481import UIAbility from '@ohos.app.ability.UIAbility'; 482import { BusinessError } from '@ohos.base' 483import window from '@ohos.window'; 484 485class EntryAbility extends UIAbility { 486 onWindowStageCreate(windowStage: window.WindowStage) { 487 let promise = dataPreferences.deletePreferences(this.context, 'myStore'); 488 promise.then(() => { 489 console.info("Succeeded in deleting preferences."); 490 }).catch((err: BusinessError) => { 491 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 492 }) 493 } 494} 495``` 496 497## dataPreferences.deletePreferences<sup>10+</sup> 498 499deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void 500 501Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result. 502 503After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. 504 505**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 506 507**Parameters** 508 509| Name | Type | Mandatory| Description | 510| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 511| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 512| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 513| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 514 515**Error codes** 516 517For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 518 519| ID| Error Message | 520| -------- | ---------------------------------- | 521| 15500010 | Failed to delete preferences file. | 522| 15501001 | Only supported in stage mode. | 523| 15501002 | The data group id is not valid. | 524 525**Example** 526 527FA model: 528 529```ts 530// Obtain the context. 531import featureAbility from '@ohos.ability.featureAbility'; 532import { BusinessError } from '@ohos.base' 533 534let context = featureAbility.getContext(); 535 536let options: dataPreferences.Options = { name: 'myStore' }; 537dataPreferences.deletePreferences(context, options, (err: BusinessError) => { 538 if (err) { 539 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 540 return; 541 } 542 console.info("Succeeded in deleting preferences."); 543}) 544``` 545 546Stage model: 547 548```ts 549import UIAbility from '@ohos.app.ability.UIAbility'; 550import { BusinessError } from '@ohos.base' 551import window from '@ohos.window'; 552 553class EntryAbility extends UIAbility { 554 onWindowStageCreate(windowStage: window.WindowStage) { 555 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 556 dataPreferences.deletePreferences(this.context, options, (err: BusinessError) => { 557 if (err) { 558 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 559 return; 560 } 561 console.info("Succeeded in deleting preferences."); 562 }) 563 } 564} 565``` 566 567 568## dataPreferences.deletePreferences<sup>10+</sup> 569 570deletePreferences(context: Context, options: Options): Promise<void> 571 572Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result. 573 574After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. 575 576**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 577 578**Parameters** 579 580| Name | Type | Mandatory| Description | 581| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 582| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 583| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 584 585**Return value** 586 587| Type | Description | 588| ------------------- | ------------------------- | 589| Promise<void> | Promise that returns no value.| 590 591**Error codes** 592 593For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 594 595| ID| Error Message | 596| -------- | ---------------------------------- | 597| 15500010 | Failed to delete preferences file. | 598| 15501001 | Only supported in stage mode. | 599| 15501002 | The data group id is not valid. | 600 601**Example** 602 603FA model: 604 605```ts 606// Obtain the context. 607import featureAbility from '@ohos.ability.featureAbility'; 608import { BusinessError } from '@ohos.base' 609 610let context = featureAbility.getContext(); 611 612let options: dataPreferences.Options = { name: 'myStore' }; 613let promise = dataPreferences.deletePreferences(context, options); 614promise.then(() => { 615 console.info("Succeeded in deleting preferences."); 616}).catch((err: BusinessError) => { 617 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 618}) 619``` 620 621Stage model: 622 623```ts 624import UIAbility from '@ohos.app.ability.UIAbility'; 625import { BusinessError } from '@ohos.base' 626import window from '@ohos.window'; 627 628class EntryAbility extends UIAbility { 629 onWindowStageCreate(windowStage: window.WindowStage) { 630 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 631 let promise = dataPreferences.deletePreferences(this.context, options); 632 promise.then(() => { 633 console.info("Succeeded in deleting preferences."); 634 }).catch((err: BusinessError) => { 635 console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); 636 }) 637 } 638} 639``` 640 641 642## dataPreferences.removePreferencesFromCache 643 644removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void 645 646Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result. 647 648After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 649 650After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 651 652**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 653 654**Parameters** 655 656| Name | Type | Mandatory| Description | 657| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | 658| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 659| name | string | Yes | Name of the **Preferences** instance. | 660| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 661 662**Example** 663 664FA model: 665 666```ts 667// Obtain the context. 668import featureAbility from '@ohos.ability.featureAbility'; 669import { BusinessError } from '@ohos.base' 670 671let context = featureAbility.getContext(); 672dataPreferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => { 673 if (err) { 674 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 675 return; 676 } 677 console.info("Succeeded in removing preferences."); 678}) 679``` 680 681Stage model: 682 683```ts 684import UIAbility from '@ohos.app.ability.UIAbility'; 685import { BusinessError } from '@ohos.base' 686import window from '@ohos.window'; 687 688class EntryAbility extends UIAbility { 689 onWindowStageCreate(windowStage: window.WindowStage) { 690 dataPreferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { 691 if (err) { 692 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 693 return; 694 } 695 console.info("Succeeded in removing preferences."); 696 }) 697 } 698} 699``` 700 701## dataPreferences.removePreferencesFromCache 702 703removePreferencesFromCache(context: Context, name: string): Promise<void> 704 705Removes a **Preferences** instance from the cache. This API uses a promise to return the result. 706 707After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 708 709After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 710 711**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 712 713**Parameters** 714 715| Name | Type | Mandatory| Description | 716| ------- | ------------------------------------- | ---- | ----------------------- | 717| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 718| name | string | Yes | Name of the **Preferences** instance.| 719 720**Return value** 721 722| Type | Description | 723| ------------------- | ------------------------- | 724| Promise<void> | Promise that returns no value.| 725 726**Example** 727 728FA model: 729 730```ts 731// Obtain the context. 732import featureAbility from '@ohos.ability.featureAbility'; 733import { BusinessError } from '@ohos.base' 734 735let context = featureAbility.getContext(); 736let promise = dataPreferences.removePreferencesFromCache(context, 'myStore'); 737promise.then(() => { 738 console.info("Succeeded in removing preferences."); 739}).catch((err: BusinessError) => { 740 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 741}) 742``` 743 744Stage model: 745 746```ts 747import UIAbility from '@ohos.app.ability.UIAbility'; 748import { BusinessError } from '@ohos.base' 749import window from '@ohos.window'; 750 751class EntryAbility extends UIAbility { 752 onWindowStageCreate(windowStage: window.WindowStage) { 753 let promise = dataPreferences.removePreferencesFromCache(this.context, 'myStore'); 754 promise.then(() => { 755 console.info("Succeeded in removing preferences."); 756 }).catch((err: BusinessError) => { 757 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 758 }) 759 } 760} 761``` 762 763## dataPreferences.removePreferencesFromCacheSync<sup>10+</sup> 764 765removePreferencesFromCacheSync(context: Context, name: string): void 766 767Removes a **Preferences** instance from the cache. This API returns the result synchronously. 768 769After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 770 771After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 772 773**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 774 775**Parameters** 776 777| Name | Type | Mandatory| Description | 778| ------- | ------------------------------------- | ---- | ----------------------- | 779| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | 780| name | string | Yes | Name of the **Preferences** instance.| 781 782**Example** 783 784FA model: 785 786```ts 787// Obtain the context. 788import featureAbility from '@ohos.ability.featureAbility'; 789let context = featureAbility.getContext(); 790dataPreferences.removePreferencesFromCacheSync(context, 'myStore'); 791``` 792 793Stage model: 794 795```ts 796import UIAbility from '@ohos.app.ability.UIAbility'; 797import window from '@ohos.window'; 798 799class EntryAbility extends UIAbility { 800 onWindowStageCreate(windowStage: window.WindowStage) { 801 dataPreferences.removePreferencesFromCacheSync(this.context, 'myStore'); 802 } 803} 804``` 805 806## dataPreferences.removePreferencesFromCache<sup>10+</sup> 807 808removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void 809 810Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result. 811 812After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 813 814After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 815 816**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 817 818**Parameters** 819 820| Name | Type | Mandatory| Description | 821| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 822| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 823| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 824| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 825 826**Error codes** 827 828For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 829 830| ID| Error Message | 831| -------- | ------------------------------ | 832| 15501001 | Only supported in stage mode. | 833| 15501002 | The data group id is not valid. | 834 835**Example** 836 837FA model: 838 839```ts 840// Obtain the context. 841import featureAbility from '@ohos.ability.featureAbility'; 842import { BusinessError } from '@ohos.base' 843 844let context = featureAbility.getContext(); 845let options: dataPreferences.Options = { name: 'myStore' }; 846dataPreferences.removePreferencesFromCache(context, options, (err: BusinessError) => { 847 if (err) { 848 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 849 return; 850 } 851 console.info("Succeeded in removing preferences."); 852}) 853``` 854 855Stage model: 856 857```ts 858import UIAbility from '@ohos.app.ability.UIAbility'; 859import { BusinessError } from '@ohos.base' 860import window from '@ohos.window'; 861 862class EntryAbility extends UIAbility { 863 onWindowStageCreate(windowStage: window.WindowStage) { 864 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 865 dataPreferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { 866 if (err) { 867 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 868 return; 869 } 870 console.info("Succeeded in removing preferences."); 871 }) 872 } 873} 874``` 875 876## dataPreferences.removePreferencesFromCache<sup>10+</sup> 877 878removePreferencesFromCache(context: Context, options: Options): Promise<void> 879 880Removes a **Preferences** instance from the cache. This API uses a promise to return the result. 881 882After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 883 884After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 885 886**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 887 888**Parameters** 889 890| Name | Type | Mandatory| Description | 891| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 892| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 893| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 894 895**Return value** 896 897| Type | Description | 898| ------------------- | ------------------------- | 899| Promise<void> | Promise that returns no value.| 900 901**Error codes** 902 903For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 904 905| ID| Error Message | 906| -------- | ------------------------------ | 907| 15501001 | Only supported in stage mode. | 908| 15501002 | The data group id is not valid. | 909 910**Example** 911 912FA model: 913 914```ts 915// Obtain the context. 916import featureAbility from '@ohos.ability.featureAbility'; 917import { BusinessError } from '@ohos.base' 918 919let context = featureAbility.getContext(); 920let options: dataPreferences.Options = { name: 'myStore' }; 921let promise = dataPreferences.removePreferencesFromCache(context, options); 922promise.then(() => { 923 console.info("Succeeded in removing preferences."); 924}).catch((err: BusinessError) => { 925 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 926}) 927``` 928 929Stage model: 930 931```ts 932import UIAbility from '@ohos.app.ability.UIAbility'; 933import { BusinessError } from '@ohos.base' 934import window from '@ohos.window'; 935 936class EntryAbility extends UIAbility { 937 onWindowStageCreate(windowStage: window.WindowStage) { 938 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 939 let promise = dataPreferences.removePreferencesFromCache(this.context, options); 940 promise.then(() => { 941 console.info("Succeeded in removing preferences."); 942 }).catch((err: BusinessError) => { 943 console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); 944 }) 945 } 946} 947``` 948 949## dataPreferences.removePreferencesFromCacheSync<sup>10+</sup> 950 951removePreferencesFromCacheSync(context: Context, options: Options):void 952 953Removes a **Preferences** instance from the cache. This API returns the result synchronously. 954 955After an application calls [getPreferences](#datapreferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#datapreferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. 956 957After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. 958 959**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 960 961**Parameters** 962 963| Name | Type | Mandatory| Description | 964| ------- | --------------------- | ---- | ------------------------------------------------------------ | 965| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| 966| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | 967 968**Error codes** 969 970For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 971 972| ID| Error Message | 973| -------- | ------------------------------- | 974| 15501001 | Only supported in stage mode. | 975| 15501002 | The data group id is not valid. | 976 977**Example** 978 979FA model: 980 981```ts 982// Obtain the context. 983import featureAbility from '@ohos.ability.featureAbility'; 984let context = featureAbility.getContext(); 985let options: dataPreferences.Options = { name: 'myStore' }; 986dataPreferences.removePreferencesFromCacheSync(context, options); 987``` 988 989Stage model: 990 991```ts 992import UIAbility from '@ohos.app.ability.UIAbility'; 993import window from '@ohos.window'; 994 995class EntryAbility extends UIAbility { 996 onWindowStageCreate(windowStage: window.WindowStage) { 997 let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 998 dataPreferences.removePreferencesFromCacheSync(this.context, options); 999 } 1000} 1001``` 1002 1003## Options<sup>10+</sup> 1004 1005Represents the configuration options of a **Preferences** instance. 1006 1007**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1008 1009| Name | Type | Mandatory| Description | 1010| ----------- | ------ | ---- | ------------------------------------------------------------ | 1011| name | string | Yes | Name of the **Preferences** instance. | 1012| dataGroupId | string\|null\|undefined | No | Application group ID, which needs to be obtained from the AppGallery.<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.| 1013 1014 1015## Preferences 1016 1017Provides APIs for obtaining and modifying the stored data. 1018 1019Before calling any API of **Preferences**, you must obtain a **Preferences** instance by using [dataPreferences.getPreferences](#datapreferencesgetpreferences). 1020 1021 1022### get 1023 1024get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void 1025 1026Obtains 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. 1027 1028**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1029 1030**Parameters** 1031 1032| Name | Type | Mandatory| Description | 1033| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1034| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1035| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1036| callback | AsyncCallback<[ValueType](#valuetype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the value obtained. Otherwise, **err** is an error object.| 1037 1038**Example** 1039 1040```ts 1041import {BusinessError} from '@ohos.base'; 1042 1043preferences.get('startup', 'default', (err: BusinessError, val: dataPreferences.ValueType) => { 1044 if (err) { 1045 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1046 return; 1047 } 1048 console.info("Obtained the value of 'startup' successfully. val: " + val); 1049}) 1050``` 1051 1052### get 1053 1054get(key: string, defValue: ValueType): Promise<ValueType> 1055 1056Obtains 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. 1057 1058**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1059 1060 **Parameters** 1061 1062| Name | Type | Mandatory| Description | 1063| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1064| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1065| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1066 1067**Return value** 1068 1069| Type | Description | 1070| ----------------------------------- | ----------------------------- | 1071| Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| 1072 1073**Example** 1074 1075```ts 1076import {BusinessError} from '@ohos.base'; 1077 1078let promise = preferences.get('startup', 'default'); 1079promise.then((data: dataPreferences.ValueType) => { 1080 console.info("Got the value of 'startup'. Data: " + data); 1081}).catch((err: BusinessError) => { 1082 console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); 1083}) 1084``` 1085 1086### getSync<sup>10+</sup> 1087 1088getSync(key: string, defValue: ValueType): ValueType 1089 1090Obtains 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. 1091 1092**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1093 1094**Parameters** 1095 1096| Name | Type | Mandatory| Description | 1097| -------- | ----------------------- | ---- | ------------------------------------------------------------ | 1098| key | string | Yes | Key of the data to obtain. It cannot be empty. | 1099| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1100 1101**Return value** 1102 1103| Type | Description | 1104| ----------------------------------- | ----------------------------- | 1105| [ValueType](#valuetype) | Returns the value obtained.| 1106 1107**Example** 1108 1109```ts 1110let value: dataPreferences.ValueType = preferences.getSync('startup', 'default'); 1111``` 1112 1113### getAll 1114 1115getAll(callback: AsyncCallback<Object>): void; 1116 1117Obtains all KV pairs from this **Preferences** instance. This API uses an asynchronous callback to return the result. 1118 1119**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1120 1121**Parameters** 1122 1123| Name | Type | Mandatory| Description | 1124| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1125| callback | AsyncCallback<Object> | Yes | Callback invoked 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.| 1126 1127**Example** 1128 1129```ts 1130import {BusinessError} from '@ohos.base'; 1131 1132// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1133// 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. 1134function getObjKeys(obj: Object): string[] { 1135 let keys = Object.keys(obj); 1136 return keys; 1137} 1138 1139preferences.getAll((err: BusinessError, value: Object) => { 1140 if (err) { 1141 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1142 return; 1143 } 1144 let allKeys = getObjKeys(value); 1145 console.info("getAll keys = " + allKeys); 1146 console.info("getAll object = " + JSON.stringify(value)); 1147}) 1148``` 1149 1150 1151### getAll 1152 1153getAll(): Promise<Object> 1154 1155Obtains all KV pairs from this **Preferences** instance. This API uses a promise to return the result. 1156 1157**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1158 1159**Return value** 1160 1161| Type | Description | 1162| --------------------- | ------------------------------------------- | 1163| Promise<Object> | Promise used to return the KV pairs obtained.| 1164 1165**Example** 1166 1167```ts 1168import {BusinessError} from '@ohos.base'; 1169 1170// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1171// 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. 1172function getObjKeys(obj: Object): string[] { 1173 let keys = Object.keys(obj); 1174 return keys; 1175} 1176 1177let promise = preferences.getAll(); 1178promise.then((value: Object) => { 1179 let allKeys = getObjKeys(value); 1180 console.info('getAll keys = ' + allKeys); 1181 console.info("getAll object = " + JSON.stringify(value)); 1182}).catch((err: BusinessError) => { 1183 console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); 1184}) 1185``` 1186 1187### getAllSync<sup>10+</sup> 1188 1189getAllSync(): Object 1190 1191Obtains all KV pairs from this **Preferences** instance. This API returns the result synchronously. 1192 1193**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1194 1195**Return value** 1196 1197| Type | Description | 1198| --------------------- | ------------------------------------------- | 1199| Object | Returns all KV pairs obtained.| 1200 1201**Example** 1202 1203```ts 1204// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. 1205// 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. 1206function getObjKeys(obj: Object): string[] { 1207 let keys = Object.keys(obj); 1208 return keys; 1209} 1210 1211let value = preferences.getAllSync(); 1212let allKeys = getObjKeys(value); 1213console.info('getAll keys = ' + allKeys); 1214console.info("getAll object = " + JSON.stringify(value)); 1215``` 1216 1217### put 1218 1219put(key: string, value: ValueType, callback: AsyncCallback<void>): void 1220 1221Writes 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. 1222 1223**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1224 1225**Parameters** 1226 1227| Name | Type | Mandatory| Description | 1228| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1229| key | string | Yes | Key of the data. It cannot be empty. | 1230| value | [ValueType](#valuetype) | Yes | Value to write. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1231| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is written successfully, **err** is **undefined**. Otherwise, **err** is an error object. | 1232 1233**Example** 1234 1235```ts 1236import {BusinessError} from '@ohos.base'; 1237 1238preferences.put('startup', 'auto', (err: BusinessError) => { 1239 if (err) { 1240 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1241 return; 1242 } 1243 console.info("Successfully put the value of 'startup'."); 1244}) 1245``` 1246 1247 1248### put 1249 1250put(key: string, value: ValueType): Promise<void> 1251 1252Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 1253 1254**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1255 1256**Parameters** 1257 1258| Name| Type | Mandatory| Description | 1259| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1260| key | string | Yes | Key of the data. It cannot be empty. | 1261| value | [ValueType](#valuetype) | Yes | Value to write. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1262 1263**Return value** 1264 1265| Type | Description | 1266| ------------------- | ------------------------- | 1267| Promise<void> | Promise that returns no value.| 1268 1269**Example** 1270 1271```ts 1272import {BusinessError} from '@ohos.base'; 1273 1274let promise = preferences.put('startup', 'auto'); 1275promise.then(() => { 1276 console.info("Successfully put the value of 'startup'."); 1277}).catch((err: BusinessError) => { 1278 console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); 1279}) 1280``` 1281 1282 1283### putSync<sup>10+</sup> 1284 1285putSync(key: string, value: ValueType): void 1286 1287Writes data to this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 1288 1289**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1290 1291**Parameters** 1292 1293| Name| Type | Mandatory| Description | 1294| ------ | ----------------------- | ---- | ------------------------------------------------------------ | 1295| key | string | Yes | Key of the data. It cannot be empty. | 1296| value | [ValueType](#valuetype) | Yes | Value to write. The value supports the following types: number, string, boolean, Array\<number>, Array\<string>, Array\<boolean>, and Uint8Array.| 1297 1298**Example** 1299 1300```ts 1301preferences.putSync('startup', 'auto'); 1302``` 1303 1304 1305### has 1306 1307has(key: string, callback: AsyncCallback<boolean>): void 1308 1309Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses an asynchronous callback to return the result. 1310 1311**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1312 1313**Parameters** 1314 1315| Name | Type | Mandatory| Description | 1316| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | 1317| key | string | Yes | Key of the data to check. It cannot be empty. | 1318| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| 1319 1320**Example** 1321 1322```ts 1323import {BusinessError} from '@ohos.base'; 1324 1325preferences.has('startup', (err: BusinessError, val: boolean) => { 1326 if (err) { 1327 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1328 return; 1329 } 1330 if (val) { 1331 console.info("The key 'startup' is contained."); 1332 } else { 1333 console.info("The key 'startup' is not contained."); 1334 } 1335}) 1336``` 1337 1338 1339### has 1340 1341has(key: string): Promise<boolean> 1342 1343Checks whether this **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result. 1344 1345**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1346 1347**Parameters** 1348 1349| Name| Type | Mandatory| Description | 1350| ------ | ------ | ---- | ------------------------------- | 1351| key | string | Yes | Key of the data to check. It cannot be empty.| 1352 1353**Return value** 1354 1355| Type | Description | 1356| ---------------------- | ------------------------------------------------------------ | 1357| 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.| 1358 1359**Example** 1360 1361```ts 1362import { BusinessError } from '@ohos.base'; 1363 1364let promise = preferences.has('startup'); 1365promise.then((val: boolean) => { 1366 if (val) { 1367 console.info("The key 'startup' is contained."); 1368 } else { 1369 console.info("The key 'startup' is not contained."); 1370 } 1371}).catch((err: BusinessError) => { 1372 console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); 1373}) 1374``` 1375 1376 1377### hasSync<sup>10+</sup> 1378 1379hasSync(key: string): boolean 1380 1381Checks whether this **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously. 1382 1383**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1384 1385**Parameters** 1386 1387| Name| Type | Mandatory| Description | 1388| ------ | ------ | ---- | ------------------------------- | 1389| key | string | Yes | Key of the data to check. It cannot be empty.| 1390 1391**Return value** 1392 1393| Type | Description | 1394| ---------------------- | ------------------------------------------------------------ | 1395| boolean | If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| 1396 1397**Example** 1398 1399```ts 1400let isExist: boolean = preferences.hasSync('startup'); 1401if (isExist) { 1402 console.info("The key 'startup' is contained."); 1403} else { 1404 console.info("The key 'startup' is not contained."); 1405} 1406``` 1407 1408 1409### delete 1410 1411delete(key: string, callback: AsyncCallback<void>): void 1412 1413Deletes 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. 1414 1415**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1416 1417**Parameters** 1418 1419| Name | Type | Mandatory| Description | 1420| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1421| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | 1422| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1423 1424**Example** 1425 1426```ts 1427import {BusinessError} from '@ohos.base'; 1428 1429preferences.delete('startup', (err: BusinessError) => { 1430 if (err) { 1431 console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); 1432 return; 1433 } 1434 console.info("Deleted the key 'startup'."); 1435}) 1436``` 1437 1438 1439### delete 1440 1441delete(key: string): Promise<void> 1442 1443Deletes 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. 1444 1445**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1446 1447**Parameters** 1448 1449| Name| Type | Mandatory| Description | 1450| ------ | ------ | ---- | ------------------------------- | 1451| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 1452 1453**Return value** 1454 1455| Type | Description | 1456| ------------------- | ------------------------- | 1457| Promise<void> | Promise that returns no value.| 1458 1459**Example** 1460 1461```ts 1462import {BusinessError} from '@ohos.base'; 1463 1464let promise = preferences.delete('startup'); 1465promise.then(() => { 1466 console.info("Deleted the key 'startup'."); 1467}).catch((err: BusinessError) => { 1468 console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); 1469}) 1470``` 1471 1472 1473### deleteSync<sup>10+</sup> 1474 1475deleteSync(key: string): void 1476 1477Deletes a KV pair from this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 1478 1479**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1480 1481**Parameters** 1482 1483| Name| Type | Mandatory| Description | 1484| ------ | ------ | ---- | ------------------------------- | 1485| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| 1486 1487**Example** 1488 1489```ts 1490preferences.deleteSync('startup'); 1491``` 1492 1493 1494### flush 1495 1496flush(callback: AsyncCallback<void>): void 1497 1498Flushes the data in this **Preferences** instance to the persistent file. This API uses an asynchronous callback to return the result. 1499 1500**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1501 1502**Parameters** 1503 1504| Name | Type | Mandatory| Description | 1505| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1506| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1507 1508**Example** 1509 1510```ts 1511import {BusinessError} from '@ohos.base'; 1512 1513preferences.flush((err: BusinessError) => { 1514 if (err) { 1515 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1516 return; 1517 } 1518 console.info("Successfully flushed data."); 1519}) 1520``` 1521 1522 1523### flush 1524 1525flush(): Promise<void> 1526 1527Flushes the data in this **Preferences** instance to the persistent file. This API uses a promise to return the result. 1528 1529**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1530 1531**Return value** 1532 1533| Type | Description | 1534| ------------------- | ------------------------- | 1535| Promise<void> | Promise that returns no value.| 1536 1537**Example** 1538 1539```ts 1540import {BusinessError} from '@ohos.base'; 1541 1542let promise = preferences.flush(); 1543promise.then(() => { 1544 console.info("Successfully flushed data."); 1545}).catch((err: BusinessError) => { 1546 console.error("Failed to flush. code =" + err.code + ", message =" + err.message); 1547}) 1548``` 1549 1550 1551### clear 1552 1553clear(callback: AsyncCallback<void>): void 1554 1555Clears this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 1556 1557**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1558 1559**Parameters** 1560 1561| Name | Type | Mandatory| Description | 1562| -------- | ------------------------- | ---- | ---------------------------------------------------- | 1563| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 1564 1565**Example** 1566 1567```ts 1568import {BusinessError} from '@ohos.base'; 1569 1570preferences.clear((err: BusinessError) =>{ 1571 if (err) { 1572 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1573 return; 1574 } 1575 console.info("Successfully cleared data."); 1576}) 1577``` 1578 1579 1580### clear 1581 1582clear(): Promise<void> 1583 1584Clears this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. 1585 1586**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1587 1588**Return value** 1589 1590| Type | Description | 1591| ------------------- | ------------------------- | 1592| Promise<void> | Promise that returns no value.| 1593 1594**Example** 1595 1596```ts 1597import {BusinessError} from '@ohos.base'; 1598 1599let promise = preferences.clear(); 1600promise.then(() => { 1601 console.info("Successfully cleared data."); 1602}).catch((err: BusinessError) => { 1603 console.error("Failed to clear. code =" + err.code + ", message =" + err.message); 1604}) 1605``` 1606 1607 1608### clearSync<sup>10+</sup> 1609 1610clearSync(): void 1611 1612Clears this **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. 1613 1614**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1615 1616**Example** 1617 1618```ts 1619preferences.clearSync(); 1620``` 1621 1622 1623### on('change') 1624 1625on(type: 'change', callback: Callback<string>): void 1626 1627Subscribes to data changes. A callback will be triggered to return the new value if the value of the subscribed key is changed and [flushed](#flush). 1628 1629**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1630 1631**Parameters** 1632 1633| Name | Type | Mandatory| Description | 1634| -------- | -------- | ---- | ---------------------------------------- | 1635| type | string | Yes | Event type. The value **change** indicates data changes.| 1636| callback | Callback<string> | Yes | Callback invoked to return data changes. | 1637 1638**Example** 1639 1640```ts 1641import {BusinessError} from '@ohos.base'; 1642 1643let observer = (key: string) => { 1644 console.info("The key " + key + " changed."); 1645} 1646preferences.on('change', observer); 1647preferences.putSync('startup', 'manual'); 1648preferences.flush((err: BusinessError) => { 1649 if (err) { 1650 console.error("Failed to flush. Cause: " + err); 1651 return; 1652 } 1653 console.info("Successfully flushed data."); 1654}) 1655``` 1656 1657### on('multiProcessChange')<sup>10+</sup> 1658 1659on(type: 'multiProcessChange', callback: Callback<string>): void 1660 1661Subscribes to inter-process data changes. For the multiple processes holding the same preference file, if the value of the subscribed key changes in any process, the callback in this API will be invoked after [flush()](#flush) is executed. 1662 1663**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1664 1665**Parameters** 1666 1667| Name | Type | Mandatory| Description | 1668| -------- | -------- | ---- | ------------------------------------------------------------ | 1669| type | string | Yes | Event type. The value is **multiProcessChange**, which indicates data changes between multiple processes.| 1670| callback | Callback<string> | Yes | Callback invoked to return inter-process data changes. | 1671 1672**Error codes** 1673 1674For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). 1675 1676| ID| Error Message | 1677| -------- | -------------------------------------- | 1678| 15500019 | Failed to obtain subscription service. | 1679 1680**Example** 1681 1682```ts 1683import {BusinessError} from '@ohos.base'; 1684 1685let observer = (key: string) => { 1686 console.info("The key " + key + " changed."); 1687} 1688preferences.on('multiProcessChange', observer); 1689preferences.putSync('startup', 'manual'); 1690preferences.flush((err: BusinessError) => { 1691 if (err) { 1692 console.error("Failed to flush. Cause: " + err); 1693 return; 1694 } 1695 console.info("Successfully flushed data."); 1696}) 1697``` 1698 1699### off('change') 1700 1701off(type: 'change', callback?: Callback<string>): void 1702 1703Unsubscribes from data changes. 1704 1705**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1706 1707**Parameters** 1708 1709| Name | Type | Mandatory| Description | 1710| -------- | -------- | ---- | ------------------------------------------------------------ | 1711| type | string | Yes | Event type. The value **change** indicates data changes. | 1712| callback | Callback<string> | No | Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered.| 1713 1714**Example** 1715 1716```ts 1717import {BusinessError} from '@ohos.base'; 1718 1719let observer = (key: string) => { 1720 console.info("The key " + key + " changed."); 1721} 1722preferences.on('change', observer); 1723preferences.putSync('startup', 'auto'); 1724preferences.flush((err: BusinessError) => { 1725 if (err) { 1726 console.error("Failed to flush. Cause: " + err); 1727 return; 1728 } 1729 console.info("Successfully flushed data."); 1730}) 1731preferences.off('change', observer); 1732``` 1733 1734### off('multiProcessChange')<sup>10+</sup> 1735 1736off(type: 'multiProcessChange', callback?: Callback<string>): void 1737 1738Unsubscribes from inter-process data changes. 1739 1740**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1741 1742**Parameters** 1743 1744| Name | Type | Mandatory| Description | 1745| -------- | -------- | ---- | ------------------------------------------------------------ | 1746| type | string | Yes | Event type. The value is **multiProcessChange**, which indicates data changes between multiple processes.| 1747| callback | Callback<string> | No | Callback to unregister. If this parameter is left blank, all callbacks for inter-process data changes will be unregistered.| 1748 1749**Example** 1750 1751```ts 1752import {BusinessError} from '@ohos.base'; 1753 1754let observer = (key: string) => { 1755 console.info("The key " + key + " changed."); 1756} 1757preferences.on('multiProcessChange', observer); 1758preferences.putSync('startup', 'auto'); 1759preferences.flush((err: BusinessError) => { 1760 if (err) { 1761 console.error("Failed to flush. Cause: " + err); 1762 return; 1763 } 1764 console.info("Successfully flushed data."); 1765}) 1766preferences.off('multiProcessChange', observer); 1767``` 1768## ValueType 1769 1770Enumerates the value types. 1771 1772**System capability**: SystemCapability.DistributedDataManager.Preferences.Core 1773 1774| Type | Description | 1775| --------------- | --------------------------------- | 1776| number | The value is a number. | 1777| string | The value is a string. | 1778| boolean | The value is true or false. | 1779| Array\<number> | The value is an array of numbers. | 1780| Array\<boolean> | The value is a Boolean array. | 1781| Array\<string> | The value is an array of strings. | 1782| Uint8Array<sup>11+</sup> | The value is an array of 8-bit unsigned integers.| 1783