1# @ohos.data.dataShare (Data Sharing) 2 3The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. 4 5> **NOTE** 6> 7> - 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. 8> 9> - The APIs provided by this module are system APIs. 10> 11> - The APIs of this module can be used only in the stage model. 12 13 14## Modules to Import 15 16```ts 17import dataShare from '@ohos.data.dataShare' 18``` 19 20## dataShare.createDataShareHelper 21 22createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void 23 24Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 25 26Observe the following when using this API: 27 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 28 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 29 - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 30 31**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 32 33**Parameters** 34 35| Name | Type | Mandatory| Description | 36| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 37| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 38| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | 39| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| 40 41**Error codes** 42 43For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 44 45| ID| Error Message | 46| -------- | ---------------------------------------------------- | 47| 15700010 | The DataShareHelper is not initialized successfully. | 48 49**Example** 50 51```ts 52import { BusinessError } from '@ohos.base' 53 54let uri = ("datashare:///com.samples.datasharetest.DataShare"); 55let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 56try { 57 dataShare.createDataShareHelper(this.context, uri, (err, data) => { 58 if (err !== undefined) { 59 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 60 return; 61 } 62 console.info("createDataShareHelper succeed, data : " + data); 63 dataShareHelper = data; 64 }); 65} catch (err) { 66 let code = (err as BusinessError).code; 67 let message = (err as BusinessError).message; 68 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 69}; 70``` 71 72## dataShare.createDataShareHelper<sup>10+</sup> 73createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void 74 75Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 76 77Observe the following when using this API: 78 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 79 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 80 - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 81 82**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 83 84 85| Name | Type | Mandatory| Description | 86| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 87| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 88| uri | string | Yes | URI of the server application to connect. | 89| options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Configuration specifying whether [DataShareHelper](#datasharehelper) is in proxy mode.| 90| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| 91 92**Error codes** 93 94For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 95 96| ID| Error Message | 97| -------- | ---------------------------------------------------- | 98| 15700010 | The DataShareHelper is not initialized successfully. | 99 100**Example** 101 102```ts 103import { BusinessError } from '@ohos.base' 104 105let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 106let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 107try { 108 dataShare.createDataShareHelper(this.context, uri, {isProxy : true}, (err, data) => { 109 if (err !== undefined) { 110 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 111 return; 112 } 113 console.info("createDataShareHelper succeed, data : " + data); 114 dataShareHelper = data; 115 }); 116} catch (err) { 117 let code = (err as BusinessError).code; 118 let message = (err as BusinessError).message; 119 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 120}; 121``` 122## dataShare.createDataShareHelper 123 124createDataShareHelper(context: Context, uri: string, options?: DataShareHelperOptions): Promise<DataShareHelper> 125 126Creates a **DataShareHelper** instance. This API uses a promise to return the result. 127 128Observe the following when using this API: 129 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 130 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 131 - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 132 133**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 134 135**Parameters** 136 137| Name | Type | Mandatory| Description | 138| ------- | ------------------------------------------------- | ---- | ------------------------------ | 139| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 140| uri | string | Yes | URI of the server application to connect.| 141| options | [DataShareHelperOptions](#datasharehelperoptions10) | No| Configuration of the **DataShareHelper** instance. This parameter is supported from API version 10. If it is not set, [DataShareHelper](#datasharehelper) is not in proxy mode. | 142 143**Return value** 144 145| Type | Description | 146| -------------------------------------------------- | -------------------------------------- | 147| Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| 148 149**Error codes** 150 151For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 152 153| ID| Error Message | 154| -------- | ---------------------------------------------------- | 155| 15700010 | The DataShareHelper is not initialized successfully. | 156 157**Example** 158 159```ts 160import { BusinessError } from '@ohos.base' 161 162let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 163let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 164try { 165 dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data: dataShare.DataShareHelper) => { 166 console.info("createDataShareHelper succeed, data : " + data); 167 dataShareHelper = data; 168 }). catch((err: BusinessError) => { 169 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 170 }); 171} catch (err) { 172 let code = (err as BusinessError).code; 173 let message = (err as BusinessError).message; 174 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 175}; 176``` 177 178## DataShareHelperOptions<sup>10+</sup> 179 180Defines whether [DataShareHelper](#datasharehelper) is in proxy mode. 181 182**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 183 184| Name| Type| Mandatory| Description| 185| -------- | -------- | -------- | -------- | 186| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode.<br/>The default value is **false**.<br>If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper](#datasharecreatedatasharehelper10) will start the data provider to create a database. | 187 188## TemplateId<sup>10+</sup> 189 190Defines the **TemplateId** struct. **TemplateId** is generated by [**addTemplate**](#addtemplate10) to identify a template. 191 192**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 193 194| Name| Type| Mandatory| Description| 195| -------- | -------- | -------- | -------- | 196| subscriberId | string | Yes| ID of the subscriber who handles the callback. The value must the same as the **subscriberId** in [**addTemplate**](#addtemplate10). The ID of each subscriber must be unique.| 197| bundleNameOfOwner | string | Yes| Bundle name of the template owner. The value must be the same as the **bundleName** in [**addTemplate**](#addtemplate10).| 198 199## PublishedItem<sup>10+</sup> 200 201Defines the data to publish. 202 203**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 204 205| Name| Type| Mandatory| Description| 206| -------- | -------- | -------- | -------- | 207| key | string | Yes| Key of the data to publish.| 208| data | string \| ArrayBuffer | Yes| Data to publish. If the data to publish exceeds 20 KB, you are advised to use **data** of the ArrayBuffer type. | 209| subscriberId | string | Yes| Subscriber ID.| 210 211## RdbDataChangeNode<sup>10+</sup> 212 213Defines the subscription/unsubscription result of the RDB data changes. 214 215**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 216 217| Name| Type| Mandatory| Description| 218| -------- | -------- | -------- | -------- | 219| uri | string | Yes| URI of the callback.| 220| templateId | [TemplateId](#templateid10) | Yes| ID of the template that triggers the callback.| 221| data | Array<string> | Yes| Data of the callback.| 222 223## PublishedDataChangeNode<sup>10+</sup> 224 225Defines the subscription/unsubscription result of the changes in the published data. 226 227**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 228 229| Name| Type| Mandatory| Description| 230| -------- | -------- | -------- | -------- | 231| bundleName | string | Yes| Bundle name of the callback.| 232| data | Array<[PublishedItem](#publisheditem10)> | Yes| Data of the callback.| 233 234## Template<sup>10+</sup> 235 236Defines the struct of the template used in a subscription. 237 238**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 239 240| Name| Type| Mandatory| Description| 241| -------- | -------- | -------- | -------- | 242| predicates | { [key: string]: string } | Yes| Predicates to use. When [**on**](#onrdbdatachange10) is called, the predicates are used to generate data. This parameter applies only to RDB data storage. | 243| scheduler | string | Yes| Template scheduler SQL, which is embedded with a custom function. Currently, the **remindTimer** function is embedded. The **remindTimer** triggers a subscription-based update in specified scenarios.<br>The scheduler SQL statement is triggered when:<br>1. The subscribed data is modified.<br>2. The first subscription is added to the corresponding database.| 244 245## OperationResult<sup>10+</sup> 246 247Defines the result of the operation for subscribing to or unsubscribing from the data changes or published data. 248 249**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 250 251| Name| Type| Mandatory| Description| 252| -------- | -------- | ----- | -------- | 253| key | string | Yes| Key of the operation result.| 254| result | number | Yes| Operation result. If the operation is successful, **0** is returned; otherwise, an error code is returned. | 255## DataShareHelper 256 257Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). 258 259### on('dataChange') 260 261on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void 262 263Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result. 264 265**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 266 267**Parameters** 268 269| Name | Type | Mandatory| Description | 270| -------- | -------------------- | ---- | ------------------------ | 271| type | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 272| uri | string | Yes | URI of the data.| 273| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| 274 275**Example** 276 277```ts 278let onCallback: () => void = (): void => { 279 console.info("**** Observer on callback ****"); 280} 281let uri = ("datashare:///com.samples.datasharetest.DataShare"); 282if (dataShareHelper !== undefined) { 283 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, onCallback); 284} 285``` 286 287### off('dataChange') 288 289off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void 290 291Unsubscribes from data changes. 292 293**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 294 295**Parameters** 296 297| Name | Type | Mandatory| Description | 298| -------- | -------------------- | ---- | ------------------------ | 299| type | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 300| uri | string | Yes | URI of the target data.| 301| callback | AsyncCallback<void> | No | Callback for the data change. If this parameter is left empty, all notification events of the URI will be unsubscribed from. | 302 303**Example** 304 305```ts 306let callback: () => void = (): void => { 307 console.info("**** Observer on callback ****"); 308} 309let uri = ("datashare:///com.samples.datasharetest.DataShare"); 310if (dataShareHelper != undefined) { 311 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, callback); 312 (dataShareHelper as dataShare.DataShareHelper).off("dataChange", uri, callback); 313} 314``` 315 316### addTemplate<sup>10+</sup> 317 318addTemplate(uri: string, subscriberId: string, template: Template): void 319 320Adds a data template with the specified subscriber. 321 322**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 323 324**Parameters** 325 326| Name | Type | Mandatory| Description | 327| -------- | ------------------------ | ---- | -------------------------| 328| uri | string | Yes | URI of the data template to add. | 329| subscriberId | string | Yes | Unique ID of the template subscriber.| 330| template | [Template](#template10) | Yes | Data template to add. | 331 332**Error codes** 333 334For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 335 336| ID| Error Message | 337| -------- | -------------------- | 338| 15700011 | The uri is not exist.| 339 340**Example** 341 342```ts 343let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 344let subscriberId = '11'; 345let key1: string = "p1"; 346let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 347let key2: string = "p2"; 348let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 349let template: dataShare.Template = { 350 predicates : { 351 key1 : value1, 352 key2 : value2, 353 }, 354 scheduler : "select remindTimer(time) from TBL00" 355} 356if (dataShareHelper != undefined) { 357 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 358} 359``` 360 361### delTemplate<sup>10+</sup> 362 363delTemplate(uri: string, subscriberId: string): void 364 365Deletes a data template based on the specified subscriber. 366 367**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 368 369**Parameters** 370 371| Name | Type | Mandatory| Description | 372| -------- | -------------| ---- | ------------------------- | 373| uri | string | Yes | URI of the data template to delete. | 374| subscriberId | string | Yes | Unique ID of the subscriber. | 375 376**Error codes** 377 378For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 379 380| ID| Error Message | 381| -------- | -------------------- | 382| 15700011 | The uri is not exist.| 383 384**Example** 385 386```ts 387let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 388let subscriberId = '11'; 389let key1: string = "p1"; 390let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 391let key2: string = "p2"; 392let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 393let template: dataShare.Template = { 394 predicates : { 395 key1 : value1, 396 key2 : value2, 397 }, 398 scheduler : "select remindTimer(time) from TBL00" 399} 400if (dataShareHelper != undefined) { 401 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 402 (dataShareHelper as dataShare.DataShareHelper).delTemplate(uri, subscriberId); 403} 404``` 405 406### on('rdbDataChange')<sup>10+</sup> 407 408on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 409 410Subscribes to the changes of the data corresponding to the specified URI and template. 411 412**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 413 414**Parameters** 415 416| Name | Type | Mandatory| Description | 417| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 418| type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the RDB data change event. If **type** is any other value, there is no response to this API. | 419| uris | Array<string> | Yes | URIs of the data to operate. | 420| templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 421| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | Yes | Callback invoked to return the result when the specified data changes. The **err** is **undefined**, and **node** is the new data. Otherwise, this callback is not triggered or **err** is an error object. | 422 423**Return value** 424 425| Type | Description | 426| ---------------- | ------------------------------------------------------------ | 427| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 428 429**Example** 430 431```ts 432import { BusinessError } from '@ohos.base' 433 434let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => { 435 console.info("onCallback " + JSON.stringify(node.uri)); 436 console.info("onCallback " + JSON.stringify(node.templateId)); 437 console.info("onCallback " + node.data.length); 438 for (let i = 0; i < node.data.length; i++) { 439 console.info("onCallback " + typeof node.data[i] + " " + node.data[i]); 440 } 441} 442 443let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 444let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 445if (dataShareHelper != undefined) { 446 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on("rdbDataChange", [uri], templateId, onCallback); 447} 448``` 449 450### off('rdbDataChange')<sup>10+</sup> 451 452off(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback?: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 453 454Unsubscribes from the changes of the data corresponding to the specified URI and template. 455 456**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 457 458**Parameters** 459 460| Name | Type | Mandatory| Description | 461| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 462| type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the RDB data changes. | 463| uris | Array<string> | Yes | URIs of the data to operate. | 464| templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 465| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | No | Callback for the RDB data change. If this parameter is left empty, all notification events of the URI will be unsubscribed from. | 466 467**Return value** 468 469| Type | Description | 470| ---------------- | ------------------------------------------------------------ | 471| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 472 473**Example** 474 475```ts 476let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 477let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 478if (dataShareHelper != undefined) { 479 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("rdbDataChange", [uri], templateId); 480} 481``` 482 483### on('publishedDataChange')<sup>10+</sup> 484 485on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 486 487Subscribes to changes of the published data. 488 489**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 490 491**Parameters** 492 493| Name | Type | Mandatory| Description | 494| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 495| type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the event of published data changes. | 496| uris | Array<string> | Yes | URIs of the data to operate. | 497| subscriberId | string | Yes | Subscriber ID of the callback. | 498| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | Yes | Callback invoked to return the result when the published data changes. The **err** is **undefined**, and **node** is the new data. Otherwise, this callback is not triggered or **err** is an error object. | 499 500**Return value** 501 502| Type | Description | 503| ---------------- | ------------------------------------------------------------ | 504| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 505 506**Example** 507 508```ts 509import { BusinessError } from '@ohos.base' 510 511let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 512 console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); 513 console.info("onPublishCallback node data size" + node.data.length); 514 for (let i = 0; i < node.data.length; i++) { 515 console.info("onPublishCallback node " + typeof node.data[i].data); 516 if (typeof node.data[i].data != 'string') { 517 let array: ArrayBuffer = node.data[i].data as ArrayBuffer; 518 let data: Uint8Array = new Uint8Array(array); 519 console.info("onPublishCallback " + i + " " + JSON.stringify(data)); 520 } 521 console.info("onPublishCallback data " + i + " " + JSON.stringify(node.data[i])); 522 } 523} 524let uris:Array<string> = ['city', 'datashareproxy://com.acts.ohos.data.datasharetest/appInfo', 'key2']; 525let subscriberId = '11'; 526if (dataShareHelper != undefined) { 527 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on('publishedDataChange', uris, subscriberId, onPublishCallback); 528} 529``` 530 531### off('publishedDataChange')<sup>10+</sup> 532 533off(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback?: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 534 535Unsubscribes from the changes of the published data. 536 537**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 538 539**Parameters** 540 541| Name | Type | Mandatory| Description | 542| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 543| type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the published data changes. | 544| uris | Array<string> | Yes | URIs of the data to operate. | 545| subscriberId | string | Yes | Subscriber ID of the callback. | 546| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | No | Callback for the published data change. If this parameter is left empty, all callbcks of the URI will be unregistered.| 547 548**Return value** 549 550| Type | Description | 551| ---------------- | ------------------------------------------------------------ | 552| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 553 554**Example** 555 556```ts 557import { BusinessError } from '@ohos.base' 558 559let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 560 console.info("**** Observer off callback ****"); 561} 562let uris:Array<string> = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; 563let subscriberId = '11'; 564if (dataShareHelper != undefined) { 565 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("publishedDataChange", uris, subscriberId, offCallback); 566} 567``` 568 569### publish<sup>10+</sup> 570 571publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void 572 573Publishes data to the database. 574 575**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 576 577**Parameters** 578 579| Name | Type | Mandatory| Description | 580| --------- | -------------------------------------------------| ---- | ------------------- | 581| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 582| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 583| version | number | Yes | Version of the data to publish. A larger value indicates a later data version. If the version of the data published is earlier than that of the data in the database, the data in the database will not be updated.| 584| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback invoked to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback will not be triggered or **err** is an error object. | 585 586**Error codes** 587 588For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 589 590| ID| Error Message | 591| -------- | -------------------------- | 592| 15700012 | The data area is not exist.| 593 594**Example** 595 596```ts 597import { BusinessError } from '@ohos.base' 598 599let arrayBuffer = new ArrayBuffer(1); 600let version = 1; 601let dataArray : Array<dataShare.PublishedItem> = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; 602let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 603 console.info("publishCallback " + JSON.stringify(result)); 604} 605try { 606 console.info("dataArray length is:", dataArray.length); 607 if (dataShareHelper != undefined) { 608 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", version, publishCallback); 609 } 610} catch (e) { 611 console.error("publish error " + JSON.stringify(e)); 612} 613``` 614 615### publish<sup>10+</sup> 616 617publish(data: Array<PublishedItem>, bundleName: string, callback: AsyncCallback<Array<OperationResult>>): void 618 619Publishes data to the database. 620 621**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 622 623**Parameters** 624 625| Name | Type | Mandatory| Description | 626| -------- | ------------------------------------------------- | ---- | ---------------------------------- | 627| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 628| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 629| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback invoked to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback will not be triggered or **err** is an error object.| 630 631**Example** 632 633**Error codes** 634 635For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 636 637| ID| Error Message | 638| -------- | -------------------------- | 639| 15700012 | The data area is not exist.| 640 641```ts 642import { BusinessError } from '@ohos.base' 643 644let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 645 console.info("publishCallback " + JSON.stringify(result)); 646} 647let dataArray : Array<dataShare.PublishedItem> = [ 648 {key:"city", subscriberId:"11", data:"xian"}, 649 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 650 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 651if (dataShareHelper != undefined) { 652 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", publishCallback); 653} 654``` 655 656### publish<sup>10+</sup> 657 658publish(data: Array<PublishedItem>, bundleName: string, version?: number): Promise<Array<OperationResult>> 659 660Publishes data to the database. 661 662**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 663 664**Parameters** 665 666| Name | Type | Mandatory| Description | 667| -------- | ----------------------------- | ---- | ------------------------------ | 668| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish.| 669| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 670| version | number | No | Version of the data to publish. A larger value indicates a later data version. If the version of the data published is earlier than that of the data in the database, the data in the database will not be updated.<br>If the data version is not checked, leave this parameter unspecified.| 671 672**Return value** 673 674| Type | Description | 675| ---------------- | ------------------------------------------------------------ | 676| Promise<Array<[OperationResult](#operationresult10)>> | Returns the operation result.| 677 678**Error codes** 679 680For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 681 682| ID| Error Message | 683| -------- | -------------------------- | 684| 15700012 | The data area is not exist.| 685 686**Example** 687 688```ts 689let dataArray: Array<dataShare.PublishedItem> = [ 690 {key:"city", subscriberId:"11", data:"xian"}, 691 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 692 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 693if (dataShareHelper != undefined) { 694 let result: Promise<Array<dataShare.OperationResult>> = (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest"); 695} 696``` 697 698### getPublishedData<sup>10+</sup> 699 700getPublishedData(bundleName: string, callback: AsyncCallback<Array<PublishedItem>>): void 701 702Obtains the published data of an application. 703 704**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 705 706**Parameters** 707 708| Name | Type | Mandatory| Description | 709| -------- | -----------------| ---- | ----------------------------- | 710| bundleName | string | Yes | Application to which the data belongs. | 711| callback | AsyncCallback<Array<[PublishedItem](#publisheditem10)>> | Yes | Callback invoked to return the result.| 712 713**Error codes** 714 715For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 716 717| ID| Error Message | 718| -------- | -------------------------- | 719| 15700012 | The data area is not exist.| 720 721**Example** 722 723```ts 724import { BusinessError } from '@ohos.base' 725 726let publishCallback: (err: BusinessError, data: Array<dataShare.PublishedItem>) => void = (err: BusinessError, result: Array<dataShare.PublishedItem>): void => { 727 console.info("**** Observer publish callback ****"); 728} 729if (dataShareHelper != undefined) { 730 (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); 731} 732``` 733 734### getPublishedData<sup>10+</sup> 735 736getPublishedData(bundleName: string): Promise<Array<PublishedItem>> 737 738Obtains the published data of an application. 739 740**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 741 742**Parameters** 743 744| Name | Type | Mandatory| Description | 745| -------- | --------------| ---- | -------------------------------------- | 746| bundleName | string | Yes | Application to which the data belongs. | 747 748**Return value** 749 750| Type | Description | 751| ---------------- | ------------------------------------------------------------ | 752| Promise<Array<[PublishedItem](#publisheditem10)>> | Promise used to return the data obtained.| 753 754**Error codes** 755 756For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 757 758| ID| Error Message | 759| -------- | -------------------------- | 760| 15700012 | The data area is not exist.| 761 762**Example** 763 764```ts 765if (dataShareHelper != undefined) { 766 let publishedData: Promise<Array<dataShare.PublishedItem>> = (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest"); 767} 768``` 769 770### insert 771 772insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void 773 774Inserts a single data record into the database. This API uses an asynchronous callback to return the result. 775 776**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 777 778**Parameters** 779 780| Name | Type | Mandatory| Description | 781| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | 782| uri | string | Yes | URI of the data to insert. | 783| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | 784| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.<br>The data index is not returned if the APIs of the database in use, for example, the key-value database (KVDB), do not support the return of indexes.| 785 786**Example** 787 788```ts 789import { ValuesBucket } from '@ohos.data.ValuesBucket' 790import { BusinessError } from '@ohos.base' 791 792let uri = ("datashare:///com.samples.datasharetest.DataShare"); 793let key1: string = "name"; 794let value1: string = "rose"; 795let key2: string = "age"; 796let value2: number = 22; 797let key3: string = "salary"; 798let value3: number = 200.5; 799const valueBucket: ValuesBucket = { 800 key1: value1, 801 key2: value2, 802 key3: value3, 803} 804try { 805 if (dataShareHelper != undefined) { 806 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket, (err: BusinessError, data: number) => { 807 if (err !== undefined) { 808 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 809 return; 810 } 811 console.info("insert succeed, data : " + data); 812 }); 813 } 814} catch (err) { 815 let code = (err as BusinessError).code; 816 let message = (err as BusinessError).message; 817 console.error(`insert error: code: ${code}, message: ${message} `); 818}; 819``` 820 821### insert 822 823insert(uri: string, value: ValuesBucket): Promise<number> 824 825Inserts a single data record into the database. This API uses a promise to return the result. 826 827**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 828 829**Parameters** 830 831| Name | Type | Mandatory| Description | 832| ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | 833| uri | string | Yes | URI of the data to insert. | 834| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| 835 836**Return value** 837 838| Type | Description | 839| ---------------- | ------------------------------------------------------------ | 840| Promise<number> | Promise used to return the index of the inserted data record.<br>The data index is not returned if the APIs of the database in use (for example, KVDB) do not support the return of indexes.| 841 842**Example** 843 844```ts 845import { BusinessError } from '@ohos.base' 846import { ValuesBucket } from '@ohos.data.ValuesBucket' 847 848let uri = ("datashare:///com.samples.datasharetest.DataShare"); 849let key1: string = "name"; 850let value1: string = "rose1"; 851let key2: string = "age"; 852let value2: number = 21; 853let key3: string = "salary"; 854let value3: number = 20.5; 855const valueBucket: ValuesBucket = { 856 key1: value1, 857 key2: value2, 858 key3: value3, 859} 860try { 861 if (dataShareHelper != undefined) { 862 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket).then((data: number) => { 863 console.info("insert succeed, data : " + data); 864 }).catch((err: BusinessError) => { 865 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 866 }); 867 } 868} catch (err) { 869 let code = (err as BusinessError).code; 870 let message = (err as BusinessError).message; 871 console.error(`insert error: code: ${code}, message: ${message} `); 872}; 873``` 874 875### delete 876 877delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void 878 879Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. 880 881**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 882 883**Parameters** 884 885| Name | Type | Mandatory| Description | 886| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 887| uri | string | Yes | URI of the data to delete. | 888| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| 889| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.<br>The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 890 891**Example** 892 893```ts 894import dataSharePredicates from '@ohos.data.dataSharePredicates'; 895import { BusinessError } from '@ohos.base' 896 897let uri = ("datashare:///com.samples.datasharetest.DataShare"); 898let da = new dataSharePredicates.DataSharePredicates(); 899da.equalTo("name", "ZhangSan"); 900try { 901 if (dataShareHelper != undefined) { 902 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da, (err: BusinessError, data: number) => { 903 if (err !== undefined) { 904 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 905 return; 906 } 907 console.info("delete succeed, data : " + data); 908 }); 909 } 910} catch (err) { 911 let code = (err as BusinessError).code; 912 let message = (err as BusinessError).message; 913 console.error(`delete error: code: ${code}, message: ${message} `); 914}; 915``` 916 917### delete 918 919delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise<number> 920 921Deletes one or more data records from the database. This API uses a promise to return the result. 922 923**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 924 925**Parameters** 926 927| Name | Type | Mandatory| Description | 928| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 929| uri | string | Yes | URI of the data to delete. | 930| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| 931 932**Return value** 933 934| Type | Description | 935| ---------------- | ------------------------------------------------------------ | 936| Promise<number> | Promise used to return the number of deleted data records.<br>The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 937 938**Example** 939 940```ts 941import dataSharePredicates from '@ohos.data.dataSharePredicates'; 942import { BusinessError } from '@ohos.base' 943 944let uri = ("datashare:///com.samples.datasharetest.DataShare"); 945let da = new dataSharePredicates.DataSharePredicates(); 946da.equalTo("name", "ZhangSan"); 947try { 948 if (dataShareHelper != undefined) { 949 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da).then((data: number) => { 950 console.info("delete succeed, data : " + data); 951 }).catch((err: BusinessError) => { 952 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 953 }); 954 } 955} catch (err) { 956 let code = (err as BusinessError).code; 957 let message = (err as BusinessError).message; 958 console.error(`delete error: code: ${code}, message: ${message} `); 959}; 960``` 961 962### query 963 964query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void 965 966Queries data in the database. This API uses an asynchronous callback to return the result. 967 968**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 969 970**Parameters** 971 972| Name | Type | Mandatory| Description | 973| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 974| uri | string | Yes | URI of the data to query. | 975| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| 976| columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | 977| callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| 978 979**Example** 980 981```ts 982import dataSharePredicates from '@ohos.data.dataSharePredicates'; 983import { BusinessError } from '@ohos.base' 984import DataShareResultSet from '@ohos.data.DataShareResultSet' 985 986let uri = ("datashare:///com.samples.datasharetest.DataShare"); 987let columns = ["*"]; 988let da = new dataSharePredicates.DataSharePredicates(); 989da.equalTo("name", "ZhangSan"); 990try { 991 if (dataShareHelper != undefined) { 992 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns, (err: BusinessError, data: DataShareResultSet) => { 993 if (err !== undefined) { 994 console.error(`query error: code: ${err.code}, message: ${err.message} `); 995 return; 996 } 997 console.info("query succeed, rowCount : " + data.rowCount); 998 }); 999 } 1000} catch (err) { 1001 let code = (err as BusinessError).code; 1002 let message = (err as BusinessError).message; 1003 console.error(`query error: code: ${code}, message: ${message} `); 1004}; 1005``` 1006 1007### query 1008 1009query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>): Promise<DataShareResultSet> 1010 1011Queries data in the database. This API uses a promise to return the result. 1012 1013**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1014 1015**Parameters** 1016 1017| Name | Type | Mandatory| Description | 1018| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1019| uri | string | Yes | URI of the data to query. | 1020| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| 1021| columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | 1022 1023**Return value** 1024 1025| Type | Description | 1026| ------------------------------------------------------------ | --------------------------------- | 1027| Promise<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Promise used to return the result set obtained.| 1028 1029**Example** 1030 1031```ts 1032import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1033import { BusinessError } from '@ohos.base' 1034import DataShareResultSet from '@ohos.data.DataShareResultSet' 1035 1036let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1037let columns = ["*"]; 1038let da = new dataSharePredicates.DataSharePredicates(); 1039da.equalTo("name", "ZhangSan"); 1040try { 1041 if (dataShareHelper != undefined) { 1042 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns).then((data: DataShareResultSet) => { 1043 console.info("query succeed, rowCount : " + data.rowCount); 1044 }).catch((err: BusinessError) => { 1045 console.error(`query error: code: ${err.code}, message: ${err.message} `); 1046 }); 1047 } 1048} catch (err) { 1049 let code = (err as BusinessError).code; 1050 let message = (err as BusinessError).message; 1051 console.error(`query error: code: ${code}, message: ${message} `); 1052}; 1053``` 1054 1055### update 1056 1057update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void 1058 1059Updates data in the database. This API uses an asynchronous callback to return the result. 1060 1061**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1062 1063**Parameters** 1064 1065| Name | Type | Mandatory| Description | 1066| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1067| uri | string | Yes | URI of the data to update. | 1068| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| 1069| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | 1070| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.<br>The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1071 1072**Example** 1073 1074```ts 1075import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1076import { BusinessError } from '@ohos.base' 1077import { ValuesBucket } from '@ohos.data.ValuesBucket' 1078 1079let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1080let da = new dataSharePredicates.DataSharePredicates(); 1081da.equalTo("name", "ZhangSan"); 1082let key1: string = "name"; 1083let value1: string = "roe1" 1084let key2: string = "age"; 1085let value2: number = 21 1086let key3: string = "salary"; 1087let value3: number = 20.5; 1088const va: ValuesBucket = { 1089 key1: value1, 1090 key2: value2, 1091 key3: value3, 1092} 1093try { 1094 if (dataShareHelper != undefined) { 1095 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va, (err: BusinessError, data: number) => { 1096 if (err !== undefined) { 1097 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1098 return; 1099 } 1100 console.info("update succeed, data : " + data); 1101 }); 1102 } 1103} catch (err) { 1104 let code = (err as BusinessError).code; 1105 let message = (err as BusinessError).message; 1106 console.error(`update error: code: ${code}, message: ${message} `); 1107}; 1108``` 1109 1110### update 1111 1112update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise<number> 1113 1114Updates data in the database. This API uses a promise to return the result. 1115 1116**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1117 1118**Parameters** 1119 1120| Name | Type | Mandatory| Description | 1121| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1122| uri | string | Yes | URI of the data to update. | 1123| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.<br>The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| 1124| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | 1125 1126**Return value** 1127 1128| Type | Description | 1129| ---------------- | ------------------------------------------------------------ | 1130| Promise<number> | Promise used to return the number of data records updated.<br>The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1131 1132**Example** 1133 1134```ts 1135import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1136import { ValuesBucket } from '@ohos.data.ValuesBucket' 1137import { BusinessError } from '@ohos.base' 1138 1139let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1140let da = new dataSharePredicates.DataSharePredicates(); 1141da.equalTo("name", "ZhangSan"); 1142let key1: string = "name"; 1143let value1: string = "roe1" 1144let key2: string = "age"; 1145let value2: number = 21 1146let key3: string = "salary"; 1147let value3: number = 20.5; 1148const va: ValuesBucket = { 1149 key1: value1, 1150 key2: value2, 1151 key3: value3, 1152} 1153try { 1154 if (dataShareHelper != undefined) { 1155 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va).then((data: number) => { 1156 console.info("update succeed, data : " + data); 1157 }).catch((err: BusinessError) => { 1158 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1159 }); 1160 } 1161} catch (err) { 1162 let code = (err as BusinessError).code; 1163 let message = (err as BusinessError).message; 1164 console.error(`update error: code: ${code}, message: ${message} `); 1165}; 1166``` 1167 1168### batchInsert 1169 1170batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void 1171 1172Batch inserts data into the database. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1173 1174**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1175 1176**Parameters** 1177 1178| Name | Type | Mandatory| Description | 1179| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1180| uri | string | Yes | URI of the data to insert. | 1181| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1182| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.<br>The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1183 1184**Example** 1185 1186```ts 1187import { ValuesBucket } from '@ohos.data.ValuesBucket' 1188import { BusinessError } from '@ohos.base' 1189 1190let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1191let key1: string = "name"; 1192let value11: string = "roe11" 1193let key2: string = "age"; 1194let value21: number = 21; 1195let key3: string = "salary"; 1196let value31: number = 20.5; 1197let valuesBucket1: ValuesBucket = { 1198 key1: value11, 1199 key2: value21, 1200 key3: value31, 1201} 1202let vbs = new Array(valuesBucket1); 1203try { 1204 if (dataShareHelper != undefined) { 1205 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs, (err, data) => { 1206 if (err !== undefined) { 1207 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1208 return; 1209 } 1210 console.info("batchInsert succeed, data : " + data); 1211 }); 1212 } 1213} catch (err) { 1214 let code = (err as BusinessError).code; 1215 let message = (err as BusinessError).message; 1216 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1217}; 1218``` 1219 1220### batchInsert 1221 1222batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> 1223 1224Batch inserts data into the database. This API uses a promise to return the result. Silent access is not supported currently. 1225 1226**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1227 1228**Parameters** 1229 1230| Name | Type | Mandatory| Description | 1231| ------ | ------------------------------------------------------------ | ---- | ------------------------ | 1232| uri | string | Yes | URI of the data to insert.| 1233| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1234 1235**Return value** 1236 1237| Type | Description | 1238| ---------------- | ------------------------------------------------------------ | 1239| Promise<number> | Promise used to return the number of data records inserted.<br>The number of inserted data records is not returned if the APIs of the database (for example, KVDB) in use do not the return of the number of data records.| 1240 1241**Example** 1242 1243```ts 1244import { ValuesBucket } from '@ohos.data.ValuesBucket' 1245import { BusinessError } from '@ohos.base' 1246 1247let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1248let key1: string = "name"; 1249let value11: string = "roe11" 1250let key2: string = "age"; 1251let value21: number = 21; 1252let key3: string = "salary"; 1253let value31: number = 20.5; 1254let valuesBucket1: ValuesBucket = { 1255 key1: value11, 1256 key2: value21, 1257 key3: value31, 1258} 1259let vbs = new Array(valuesBucket1); 1260try { 1261 if (dataShareHelper != undefined) { 1262 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs).then((data: number) => { 1263 console.info("batchInsert succeed, data : " + data); 1264 }).catch((err: BusinessError) => { 1265 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1266 }); 1267 } 1268} catch (err) { 1269 let code = (err as BusinessError).code; 1270 let message = (err as BusinessError).message 1271 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1272}; 1273``` 1274 1275### normalizeUri 1276 1277normalizeUri(uri: string, callback: AsyncCallback<string>): void 1278 1279Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1280 1281**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1282 1283**Parameters** 1284 1285| Name | Type | Mandatory| Description | 1286| -------- | ---------------------- | ---- | -------------------------------------------------------- | 1287| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize. | 1288| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the normalized URI (if **null** is returned, URI normalization is not supported). Otherwise, **err** is an error object.| 1289 1290**Example** 1291 1292```ts 1293import { BusinessError } from '@ohos.base' 1294 1295let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1296if (dataShareHelper != undefined) { 1297 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri, (err: BusinessError, data: string) => { 1298 if (err !== undefined) { 1299 console.info("normalizeUri failed, error message : " + err); 1300 } else { 1301 console.info("normalizeUri = " + data); 1302 } 1303 }); 1304} 1305``` 1306 1307### normalizeUri 1308 1309normalizeUri(uri: string): Promise<string> 1310 1311Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. Silent access is not supported currently. 1312 1313**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1314 1315**Parameters** 1316 1317| Name| Type | Mandatory| Description | 1318| ---- | ------ | ---- | ----------------------------------------- | 1319| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.| 1320 1321**Return value** 1322 1323| Type | Description | 1324| ---------------- | ---------------------------------------------- | 1325| Promise<string> | Promise used to return the result. If URI normalization is supported, the normalized URI is returned. Otherwise, **null** is returned.| 1326 1327**Example** 1328 1329```ts 1330import { BusinessError } from '@ohos.base' 1331 1332let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1333if (dataShareHelper != undefined) { 1334 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri).then((data: string) => { 1335 console.info("normalizeUri = " + data); 1336 }).catch((err: BusinessError) => { 1337 console.info("normalizeUri failed, error message : " + err); 1338 }); 1339} 1340``` 1341 1342### denormalizeUri 1343 1344denormalizeUri(uri: string, callback: AsyncCallback<string>): void 1345 1346Denormalizes a URI. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1347 1348**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1349 1350**Parameters** 1351 1352| Name | Type | Mandatory| Description | 1353| -------- | ---------------------- | ---- | --------------------------------------------------- | 1354| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| 1355| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the URI obtained. If the original URI is returned, denormalization is not required. If **null** is returned, denormalization is not supported. If the operation fails, **err** is an error object.| 1356 1357**Example** 1358 1359```ts 1360import { BusinessError } from '@ohos.base' 1361 1362let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1363if (dataShareHelper != undefined) { 1364 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri, (err: BusinessError, data: string) => { 1365 if (err !== undefined) { 1366 console.error("denormalizeUri failed, error message : " + err); 1367 } else { 1368 console.info("denormalizeUri = " + data); 1369 } 1370 }); 1371} 1372``` 1373 1374### denormalizeUri 1375 1376denormalizeUri(uri: string): Promise<string> 1377 1378Denormalizes a URI. This API uses a promise to return the result. Silent access is not supported currently. 1379 1380**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1381 1382**Parameters** 1383 1384| Name| Type | Mandatory| Description | 1385| ---- | ------ | ---- | ------------------------------------------- | 1386| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| 1387 1388**Return value** 1389 1390| Type | Description | 1391| ---------------- | ----------------------------------------- | 1392| Promise<string> | Promise used to return the result. If the denormalization is successful, the URI obtained is returned. If no operation is required, the original URI is returned. If denormalization is not supported, **null** is returned.| 1393 1394**Example** 1395 1396```ts 1397import { BusinessError } from '@ohos.base' 1398 1399let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1400if (dataShareHelper != undefined) { 1401 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri).then((data: string) => { 1402 console.info("denormalizeUri = " + data); 1403 }).catch((err: BusinessError) => { 1404 console.error("denormalizeUri failed, error message : " + err); 1405 }); 1406} 1407``` 1408 1409### notifyChange 1410 1411notifyChange(uri: string, callback: AsyncCallback<void>): void 1412 1413Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1414 1415**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1416 1417**Parameters** 1418 1419| Name | Type | Mandatory| Description | 1420| -------- | -------------------- | ---- | ------------------------ | 1421| uri | string | Yes | URI of the data.| 1422| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| 1423 1424**Example** 1425 1426```ts 1427let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1428if (dataShareHelper != undefined) { 1429 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri, () => { 1430 console.info("***** notifyChange *****"); 1431 }); 1432} 1433``` 1434 1435### notifyChange 1436 1437notifyChange(uri: string): Promise<void> 1438 1439Notifies the registered observer of data changes. This API uses a promise to return the result. Silent access is not supported currently. 1440 1441**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1442 1443**Parameters** 1444 1445| Name| Type | Mandatory| Description | 1446| ---- | ------ | ---- | -------------------- | 1447| uri | string | Yes | URI of the data.| 1448 1449**Return value** 1450 1451| Type | Description | 1452| -------------- | --------------------- | 1453| Promise<void> | Promise that returns no value.| 1454 1455**Example** 1456 1457```ts 1458let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1459if (dataShareHelper != undefined) { 1460 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri); 1461} 1462``` 1463