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