diff --git a/en/application-dev/database/data-sync-of-kv-store.md b/en/application-dev/database/data-sync-of-kv-store.md
index b23dd91ed1a7b4ea0cd13f6d9b49de82e1821190..39f893f799a6a4c6bf9ac2d067a5f794a6961d9c 100644
--- a/en/application-dev/database/data-sync-of-kv-store.md
+++ b/en/application-dev/database/data-sync-of-kv-store.md
@@ -32,7 +32,7 @@ The underlying devices manage the data by device. The device KV stores support d
The **DatamgrService** provides the following synchronization types:
-- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions. The manual synchronization is available only for system applications.
+- Manual synchronization: The application calls **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). You can use the [**sync()** with the **query** parameter](../reference/apis/js-apis-distributedKVStore.md#sync-1) to synchronize the data that meets the specified conditions.
- Automatic synchronization: The distributed database automatically pushes local data to the remote end and pulls remote data to the local end. An automatic synchronization is triggered when a device goes online or an application updates data.
@@ -72,8 +72,6 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
- Each KV store supports a maximum of eight callbacks for subscription of data change notifications.
-- The manual synchronization is available only for system applications.
-
## Available APIs
@@ -247,32 +245,31 @@ The following uses a single KV store as an example to describe how to implement
> **NOTE**
>
- > If manual synchronization is used, **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications.
+ > If manual synchronization is used, **deviceIds** can be obtained by [devManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
-
```js
- import deviceManager from '@ohos.distributedHardware.deviceManager';
+ import deviceManager from '@ohos.distributedDeviceManager';
let devManager;
- // create deviceManager
- deviceManager.createDeviceManager('bundleName', (err, value) => {
- if (!err) {
- devManager = value;
- // deviceIds is obtained by devManager.getTrustedDeviceListSync.
- let deviceIds = [];
- if (devManager !== null) {
- // The ohos.permission.ACCESS_SERVICE_DM permission is required. This permission is available only for system applications.
- let devices = devManager.getTrustedDeviceListSync();
- for (let i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].deviceId;
- }
- }
- try {
- // 1000 indicates the maximum delay, in ms.
- kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
- } catch (e) {
- console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
+ try {
+ // create deviceManager
+ devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
+ // deviceIds is obtained by devManager.getAvailableDeviceListSync.
+ let deviceIds = [];
+ if (devManager != null) {
+ let devices = devManager.getAvailableDeviceListSync();
+ for (let i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
}
}
- });
+ try {
+ // 1000 indicates the maximum delay, in ms.
+ kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
+ } catch (e) {
+ console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
+ }
+
+ } catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+ }
```
\ No newline at end of file
diff --git a/en/application-dev/database/data-sync-of-rdb-store.md b/en/application-dev/database/data-sync-of-rdb-store.md
index 2d6d5a73e0cf7cfae28d7d6296039e28994477a8..7bcc40f6230871e7e9a3af7150cd943b426109c1 100644
--- a/en/application-dev/database/data-sync-of-rdb-store.md
+++ b/en/application-dev/database/data-sync-of-rdb-store.md
@@ -10,9 +10,16 @@ You can synchronize the application data in a local RDB store on a device to oth
OpenHamony supports synchronization of the relational data of an application across multiple devices.
-- Distributed table list
After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name.
+- Distributed table list
-- Synchronization mode
Data can be synchronized between devices in either of the following ways:
- Pushing data from a local device to a remote device.
- Pulling data from a remote device to a local device.
+ After a table is created for an application in an RDB store, you can set it as a distributed table. When querying the RDB store of a remote device, you can obtain the distributed table name of the remote device based on the local table name.
+
+- Synchronization mode
+
+ Data can be synchronized between devices in either of the following ways:
+
+ - Pushing data from a local device to a remote device.
+ - Pulling data from a remote device to a local device.
## Working Principles
@@ -44,12 +51,10 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
- Each RDB store supports a maximum of eight callbacks for subscription of data change notifications.
-- Third-party applications cannot call the distributed APIs that must be specified with the device.
-
## Available APIs
-The following table lists the APIs for cross-device data synchronization of RDB stores. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
+Most of the APIs for cross-device data synchronization of RDB stores are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
| API| Description|
| -------- | -------- |
@@ -73,7 +78,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
import relationalStore from '@ohos.data.relationalStore';
```
-2. Request permissions.
+2. Apply for the required permission.
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
@@ -142,32 +147,33 @@ The following table lists the APIs for cross-device data synchronization of RDB
> **NOTE**
>
- > **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications.
+ > The value of **deviceIds** can be obtained by [deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
```js
// Obtain device IDs.
- import deviceManager from '@ohos.distributedHardware.deviceManager';
-
- deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`);
- return;
- }
- let devices = manager.getTrustedDeviceListSync();
- let deviceId = devices[0].deviceId;
-
- // Construct a predicate object for querying the distributed table.
- let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
- // Query data from the specified remote device and return the query result.
- store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
- function (err, resultSet) {
- if (err) {
- console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
- return;
- }
- console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
+ import deviceManager from '@ohos.distributedDeviceManager';
+ let dmInstance = null;
+ let deviceId = null;
+
+ try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+
+ // Construct a predicate object for querying the distributed table.
+ let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
+ // Query data from the specified remote device and return the query result.
+ store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
+ function (err, resultSet) {
+ if (err) {
+ console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
+ return;
}
- )
- })
- ```
+ console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
+ }
+ )
+ } catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+ }
+ ```
\ No newline at end of file
diff --git a/en/application-dev/database/share-data-by-datashareextensionability.md b/en/application-dev/database/share-data-by-datashareextensionability.md
index d3c28e31c20f0aa3d6720359aa28e84af2061a63..6b6819d706a1aadfcb6ce854189321b57657e1b3 100644
--- a/en/application-dev/database/share-data-by-datashareextensionability.md
+++ b/en/application-dev/database/share-data-by-datashareextensionability.md
@@ -57,15 +57,16 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareExtAbility.ts**.
-3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and
-override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs.
-
+3. Import **@ohos.application.DataShareExtensionAbility** and other dependencies to the **DataShareExtAbility.ts** file, and override the service implementation as required. For example, if the data provider provides only the data insertion, deletion, and query services, you can override only these APIs.
+
```js
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+ import relationalStore from '@ohos.data.relationalStore';
+ import Want from '@ohos.app.ability.Want';
```
-
+
4. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```js
@@ -75,20 +76,20 @@ override the service implementation as required. For example, if the data provid
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)';
- let rdbStore;
- let result;
+ let rdbStore: relationalStore.RdbStore;
+ let result: string;
export default class DataShareExtAbility extends Extension {
- private rdbStore_;
+ private rdbStore_: relationalStore.RdbStore;
// Override onCreate().
- onCreate(want, callback) {
+ onCreate(want: Want, callback: Function) {
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
- }, function (err, data) {
+ }, (err, data) => {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`);
@@ -100,7 +101,7 @@ override the service implementation as required. For example, if the data provid
}
// Override query().
- query(uri, predicates, columns, callback) {
+ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) {
if (predicates === null || predicates === undefined) {
console.info('invalid predicates');
}
@@ -188,6 +189,8 @@ override the service implementation as required. For example, if the data provid
import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+ import { ValuesBucket } from '@ohos.data.ValuesBucket'
+ import window from '@ohos.window';
```
2. Define the URI string for communicating with the data provider.
@@ -200,11 +203,11 @@ override the service implementation as required. For example, if the data provid
3. Create a **DataShareHelper** instance.
```js
- let dsHelper;
- let abilityContext;
+ let dsHelper: dataShare.DataShareHelper;
+ let abilityContext: Context;
export default class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => {
dsHelper = data;
@@ -217,8 +220,19 @@ override the service implementation as required. For example, if the data provid
```js
// Construct a piece of data.
- let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) };
- let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) };
+ let key1 = 'name';
+ let key2 = 'age';
+ let key3 = 'isStudent';
+ let key4 = 'Binary';
+ let valueName1 = 'ZhangSan';
+ let valueName2 = 'LiSi';
+ let valueAge1 = 21;
+ let valueAge2 = 18;
+ let valueIsStudent1 = false;
+ let valueIsStudent2 = true;
+ let valueBinary = new Uint8Array([1, 2, 3]);
+ let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary };
+ let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = ['*'];
// Insert a piece of data.
@@ -237,5 +251,4 @@ override the service implementation as required. For example, if the data provid
dsHelper.delete(dseUri, predicates, (err, data) => {
console.info(`dsHelper delete result:${data}`);
});
- ```
-
+ ```
\ No newline at end of file
diff --git a/en/application-dev/database/unified-data-channels.md b/en/application-dev/database/unified-data-channels.md
index b31b9532eafb700da67c2dbcc5464f8f58867d23..91201427f1807bb9ae002a43bf9757c26d7e2ffd 100644
--- a/en/application-dev/database/unified-data-channels.md
+++ b/en/application-dev/database/unified-data-channels.md
@@ -29,7 +29,7 @@ Currently, the UDMF provides the public data channel for cross-application data
## Available APIs
-The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [UDMF](../reference/apis/js-apis-data-udmf.md).
+The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md).
| API | Description |
|-----------------------------------------------------------------------------------------|---------------------------------------------|
@@ -45,121 +45,131 @@ The following example describes how to implement many-to-many data sharing. The
### Data Provider
-1. Import the **@ohos.data.UDMF** module.
+1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
2. Create a **UnifiedData** object and insert it into the UDMF public data channel.
```ts
- let plainText = new UDMF.PlainText();
+ import { BusinessError } from '@ohos.base';
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'hello world!';
- let unifiedData = new UDMF.UnifiedData(plainText);
+ let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// Specify the type of the data channel to which the data is to be inserted.
- let options = {
- intention: UDMF.Intention.DATA_HUB
+ let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
}
try {
- UDMF.insertData(options, unifiedData, (err, data) => {
- if (err === undefined) {
- console.info(`Succeeded in inserting data. key = ${data}`);
- } else {
- console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
- }
- });
- } catch(e) {
- console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `);
+ unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in inserting data. key = ${data}`);
+ } else {
+ console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+ } catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
}
```
3. Update the **UnifiedData** object inserted.
```ts
- let plainText = new UDMF.PlainText();
+ import { BusinessError } from '@ohos.base';
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'How are you!';
- let unifiedData = new UDMF.UnifiedData(plainText);
+ let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// Specify the URI of the UnifiedData object to update.
- let options = {
- key: 'udmf://DataHub/com.ohos.test/0123456789'
+ let options: unifiedDataChannel.Options = {
+ key: 'udmf://DataHub/com.ohos.test/0123456789'
};
try {
- UDMF.updateData(options, unifiedData, (err) => {
- if (err === undefined) {
- console.info('Succeeded in updating data.');
- } else {
- console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
- }
- });
- } catch(e) {
- console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `);
+ unifiedDataChannel.updateData(options, unifiedData, (err) => {
+ if (err === undefined) {
+ console.info('Succeeded in updating data.');
+ } else {
+ console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+ } catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
}
```
4. Delete the **UnifiedData** object from the UDMF public data channel.
```ts
+ import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be deleted.
- let options = {
- intention: UDMF.Intention.DATA_HUB
+ let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
};
-
+
try {
- UDMF.deleteData(options, (err, data) => {
- if (err === undefined) {
- console.info(`Succeeded in deleting data. size = ${data.length}`);
- for (let i = 0; i < data.length; i++) {
- let records = data[i].getRecords();
- for (let j = 0; j < records.length; j++) {
- if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
- let text = (records[j]);
- console.info(`${i + 1}.${text.textContent}`);
- }
- }
- }
- } else {
- console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
+ unifiedDataChannel.deleteData(options, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in deleting data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
}
- });
- } catch(e) {
- console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `);
+ }
+ } else {
+ console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+ } catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
}
```
### Data Consumer
-1. Import the **@ohos.data.UDMF** module.
+1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
2. Query the **UnifiedData** object in the UDMF public data channel.
```ts
+ import { BusinessError } from '@ohos.base';
// Specify the type of the data channel whose data is to be queried.
- let options = {
- intention: UDMF.Intention.DATA_HUB
+ let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
};
-
+
try {
- UDMF.queryData(options, (err, data) => {
- if (err === undefined) {
- console.info(`Succeeded in querying data. size = ${data.length}`);
- for (let i = 0; i < data.length; i++) {
- let records = data[i].getRecords();
- for (let j = 0; j < records.length; j++) {
- if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
- let text = (records[j]);
- console.info(`${i + 1}.${text.textContent}`);
- }
- }
- }
- } else {
- console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
+ unifiedDataChannel.queryData(options, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in querying data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
}
- });
+ }
+ } else {
+ console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
+ }
+ });
} catch(e) {
- console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `);
+ let error: BusinessError = e as BusinessError;
+ console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
}
```
diff --git a/en/application-dev/database/unified-data-definition.md b/en/application-dev/database/unified-data-definition.md
index d0a3c100b5dadff7ef56a0938cde5b4d98b489d4..100029b135ef0e5b267f693c79c3aa9710084981 100644
--- a/en/application-dev/database/unified-data-definition.md
+++ b/en/application-dev/database/unified-data-definition.md
@@ -5,28 +5,35 @@
To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types.
+For example, in the cross-application drag scenario, the application of the drag source writes the data to be dragged to a [drag event](../reference/arkui-ts/ts-universal-events-drag-drop.md#dragevent) based on the standard data definitions. The application of the drop target reads the dragged data from the drag event and parses the data based on the standard data definitions. The data dragged between different applications complies with the same standard definitions, which avoids exhaustive data type adaptation and effectively reduces the development workload.
## Unified Data Types
The UDMF provides the following unified data types:
-**Basic data types**
Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types.
+**Basic data types**
+
+Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types.
**Figure 1** UDMF File
![UDMF_FILE](figures/udmf_type_File.png)
-Figure 2 UDMF Text
+**Figure 2** UDMF Text
![UDMF_TEXT](figures/udmf_type_Text.png)
-**System Defined Types (SDTs)**
The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data.
+**System Defined Types (SDTs)**
+
+The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data.
**Figure 3** UDMF SDT data
![UDMF_SDT](figures/udmf_type_SDT.png)
-**App Defined Type (ADT)**
The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem.
+**App Defined Type (ADT)**
+
+The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem.
**Figure 4** UDMF ADT data
@@ -39,11 +46,11 @@ Figure 2 UDMF Text
## Available APIs
-The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UnifiedDataType**.
+The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UniformDataType**.
-The following table describes common UDMF APIs. For more information, see [UDMF](../reference/apis/js-apis-data-udmf.md).
+The following table describes common UDMF APIs. For more information about the APIs, see [Unified Data Channel](../reference/apis/js-apis-data-unifiedDataChannel.md) and [Standard Data Definition and Description](../reference/apis/js-apis-data-uniformTypeDescriptor.md).
-| Class | API | Description |
+| Class | API | Description |
|---------------|-------------------|-----------------------------------------------------------------------------------------------|
| UnifiedRecord | getType(): string | Obtains the data type of this data record.|
| UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. |
@@ -55,17 +62,19 @@ The following table describes common UDMF APIs. For more information, see [UDMF]
The following describes how to create a **UnifiedData** object containing two data records: image and plain text.
-1. Import the **@ohos.data.UDMF** module.
+1. Import the **@ohos.data.unifiedDataChannel** and **@ohos.data.uniformTypeDescriptor** modules.
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
+
2. Create an image data record and initialize the **UnifiedData** object with the image data record.
(1) Create an image data record.
```ts
- let image = new UDMF.Image();
+ let image = new unifiedDataChannel.Image();
```
(2) Modify object attributes.
@@ -84,12 +93,13 @@ The following describes how to create a **UnifiedData** object containing two da
(4) Create a **UnifiedData** instance.
```ts
- let unifiedData = new UDMF.UnifiedData(image);
+ let unifiedData = new unifiedDataChannel.UnifiedData(image);
```
-3. Create a plain text data record and add it to the **UnifiedData** instance created.
+3. Create a plain text data record and add it to the **UnifiedData** instance created.
+
```ts
- let plainText = new UDMF.PlainText();
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'this is textContent of plainText';
plainText.abstract = 'abstract of plainText';
plainText.details = {
@@ -98,25 +108,27 @@ The following describes how to create a **UnifiedData** object containing two da
};
unifiedData.addRecord(plainText);
```
+
4. Obtain all data records in this **UnifiedData** instance.
-
+
```ts
let records = unifiedData.getRecords();
```
+
5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record.
-
+
```ts
for (let i = 0; i < records.length; i ++) {
// Read the type of the data record.
let type = records[i].getType();
switch (type) {
- case UDMF.UnifiedDataType.IMAGE:
+ case uniformTypeDescriptor.UniformDataType.IMAGE:
// Convert the data to obtain the original image data record.
- let image = (records[i]);
+ let image = records[i] as unifiedDataChannel.Image;
break;
- case UDMF.UnifiedDataType.PLAIN_TEXT:
+ case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT:
// Convert the data to obtain the original text record.
- let plainText = (records[i]);
+ let plainText = records[i] as unifiedDataChannel.PlainText;
break;
default:
break;
diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
index 6691b47577dae3f00b30cda0b70b6725b5ea9495..a67d5dddcc2b862ff858d23ec70d0e16d7ab4161 100644
--- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
+++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
@@ -4,11 +4,10 @@ The **DataShareExtensionAbility** module provides data share services based on t
>**NOTE**
>
-> 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.
+> - 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.
>
-> The APIs provided by this module are system APIs.
+> - The APIs provided by this module are system APIs and can be used only in the stage model.
>
-> The APIs of this module can be used only in the stage model.
## Modules to Import
@@ -21,7 +20,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
-| Name| Type| Readable| Writable| Description|
+| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context10+ | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|DataShareExtensionAbility context, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).|
@@ -50,17 +49,17 @@ let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- onCreate(want, callback) {
+ onCreate(want: Want, callback: Function) {
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
- }, function (err, data) {
+ }, (err, data) => {
console.info(`getRdbStore done, data : ${data}`);
rdbStore = data;
- rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
+ rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.error(`executeSql done, error message : ${err}`);
});
if (callback) {
@@ -91,21 +90,22 @@ Inserts data into the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- insert(uri, valueBucket, callback) {
+ insert(uri: string, valueBucket: ValuesBucket, callback: Function) {
if (valueBucket === null) {
console.error('invalid valueBuckets');
return;
}
- rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) {
+ rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => {
console.info(`callback ret: ${ret}`);
if (callback !== undefined) {
callback(err, ret);
@@ -136,20 +136,22 @@ Updates data in the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- update(uri, predicates, valueBucket, callback) {
+ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) {
+ rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -178,20 +180,21 @@ Deletes data from the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- delete(uri, predicates, callback) {
+ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.delete(TBL_NAME, predicates, function (err, ret) {
+ rdbStore.delete(TBL_NAME, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -221,20 +224,21 @@ Queries data from the database. This API can be overridden as required.
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- query(uri, predicates, columns, callback) {
+ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
+ rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => {
if (resultSet !== undefined) {
console.info(`resultSet.rowCount: ${resultSet.rowCount}`);
}
@@ -266,21 +270,22 @@ Batch inserts data into the database. This API is called by the server and can b
```ts
import rdb from '@ohos.data.relationalStore';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- batchInsert(uri, valueBuckets, callback) {
+ batchInsert(uri: string, valueBuckets: Array, callback: Function) {
if (valueBuckets === null || valueBuckets.length === undefined) {
console.error('invalid valueBuckets');
return;
}
- rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) {
+ rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -308,11 +313,17 @@ Normalizes a URI. This API can be overridden as required.
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
- normalizeUri(uri, callback) {
- let err = {'code':0};
- let ret = `normalize: ${uri}`;
- callback(err, ret);
- }
+ normalizeUri(uri: string, callback: Function) {
+ let key = 'code';
+ let value = 0;
+ let err: BusinessError = {
+ code: value,
+ name: key,
+ message: key
+ };
+ let ret: string = `normalize: ${uri}`;
+ callback(err, ret);
+ }
};
```
@@ -335,10 +346,16 @@ Denormalizes a URI. This API can be overridden as required.
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
- denormalizeUri(uri, callback) {
- let err = {'code':0};
- let ret = `denormalize ${uri}`;
- callback(err, ret);
- }
+ denormalizeUri(uri: string, callback: Function) {
+ let key = 'code';
+ let value = 0;
+ let err: BusinessError = {
+ code: value,
+ name: key,
+ message: key
+ };
+ let ret = `denormalize ${uri}`;
+ callback(err, ret);
+ }
};
```
diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
index 020d8c43c94ccb8313a7cde1fbad39048b11395b..c03275a33751dffc03d248de48196e36afc442cd 100644
--- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
+++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
@@ -4,9 +4,9 @@ The **DataShareResultSet** module provides APIs for accessing the result set obt
> **NOTE**
>
-> 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.
+> - 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.
>
-> The APIs provided by this module are system APIs.
+> - The APIs provided by this module are system APIs.
## Modules to Import
@@ -22,8 +22,9 @@ You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShar
```ts
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'
+import { BusinessError } from '@ohos.base'
-let dataShareHelper;
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
if (err != undefined) {
@@ -36,12 +37,12 @@ await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates();
-let resultSet;
+let resultSet: DataShareResultSet;
da.equalTo("name", "ZhangSan");
-dataShareHelper.query(uri, da, columns).then((data) => {
+dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => {
console.info("query end, data : " + data);
resultSet = data;
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error("query fail, error message : " + err);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md
index ca246201a8d8be7c028f898307008bc69957a638..35c95cf2e3bcf806b9fb5bdd710eeaa5203057d3 100644
--- a/en/application-dev/reference/apis/js-apis-data-dataShare.md
+++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md
@@ -51,7 +51,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
import UIAbility from '@ohos.app.ability.UIAbility';
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-let dataShareHelper;
+let dataShareHelper: dataShare.DataShareHelper;
try {
dataShare.createDataShareHelper(this.context, uri, (err, data) => {
if (err !== undefined) {
@@ -100,7 +100,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
import UIAbility from '@ohos.app.ability.UIAbility';
let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
-let dataShareHelper;
+let dataShareHelper: dataShare.DataShareHelper;
try {
dataShare.createDataShareHelper(this.context, uri, {isProxy : true}, (err, data) => {
if (err !== undefined) {
@@ -153,14 +153,15 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
-let dataShareHelper;
+let dataShareHelper: dataShare.DataShareHelper;
try {
- dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data) => {
+ dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data: dataShare.DataShareHelper) => {
console.info("createDataShareHelper succeed, data : " + data);
dataShareHelper = data;
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -268,7 +269,8 @@ Subscribes to changes of the specified data. After an observer is registered, th
**Example**
```ts
-function onCallback() {
+let dataShareHelper: dataShare.DataShareHelper;
+let onCallback: () => void = (): void => {
console.info("**** Observer on callback ****");
}
let uri = ("datashare:///com.samples.datasharetest.DataShare");
@@ -294,8 +296,9 @@ Unsubscribes from data changes.
**Example**
```ts
-function callback() {
- console.info("**** Observer callback ****");
+let dataShareHelper: dataShare.DataShareHelper;
+let callback: () => void = (): void => {
+ console.info("**** Observer on callback ****");
}
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.on("dataChange", uri, callback);
@@ -329,12 +332,17 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
let subscriberId = '11';
-let template = {
+let key1: string = "p1";
+let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true";
+let key2: string = "p2";
+let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false";
+let template: dataShare.Template = {
predicates : {
- "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true",
- "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false",
+ key1 : value1,
+ key2 : value2,
},
scheduler : "select remindTimer(time) from TBL00"
}
@@ -367,12 +375,17 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
let subscriberId = '11';
-let template = {
+let key1: string = "p1";
+let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true";
+let key2: string = "p2";
+let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false";
+let template: dataShare.Template = {
predicates : {
- "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true",
- "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false",
+ key1 : value1,
+ key2 : value2,
},
scheduler : "select remindTimer(time) from TBL00"
}
@@ -406,7 +419,10 @@ Subscribes to the changes of the data corresponding to the specified URI and tem
**Example**
```ts
-function onCallback(err, node:dataShare.RdbDataChangeNode) {
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
+let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => {
console.info("onCallback " + JSON.stringify(node.uri));
console.info("onCallback " + JSON.stringify(node.templateId));
console.info("onCallback " + node.data.length);
@@ -446,6 +462,7 @@ Unsubscribes from the changes of the data corresponding to the specified URI and
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"};
let result:Array = dataShareHelper.off("rdbDataChange", [uri], templateId);
@@ -477,7 +494,10 @@ Subscribes to the changes of the published data.
**Example**
```ts
-function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) {
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
+let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => {
console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName));
console.info("onPublishCallback node data size" + node.data.length);
for (let i = 0; i < node.data.length; i++) {
@@ -521,7 +541,10 @@ Unsubscribes from the changes of the published data.
**Example**
```ts
-function offCallback(err, node:dataShare.PublishedDataChangeNode) {
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
+let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => {
console.info("**** Observer off callback ****");
}
let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"];
@@ -557,10 +580,13 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
let arrayBuffer = new ArrayBuffer(1);
let version = 1;
let dataArray : Array = [{key:"key2", subscriberId:"11", data:arrayBuffer}];
-function publishCallback(err, result: Array) {
+let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => {
console.info("publishCallback " + JSON.stringify(result));
}
try {
@@ -598,7 +624,10 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
| 15700012 | The data area is not exist.|
```ts
-function publishCallback(err, result: Array) {
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
+let publishCallback: (err: BusinessError, result: Array) => void = (err: BusinessError, result: Array): void => {
console.info("publishCallback " + JSON.stringify(result));
}
let dataArray : Array = [
@@ -641,11 +670,12 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
-let dataArray : Array = [
+let dataShareHelper: dataShare.DataShareHelper;
+let dataArray: Array = [
{key:"city", subscriberId:"11", data:"xian"},
{key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"},
{key:"empty", subscriberId:"11", data:"nobody sub"}];
-let result: Array = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest");
+let result: Promise> = dataShareHelper.publish(dataArray, "com.acts.ohos.data.datasharetest");
```
### getPublishedData10+
@@ -674,7 +704,10 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
-function publishCallback(err, data: Array) {
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
+let publishCallback: (err: BusinessError, data: Array) => void = (err: BusinessError, result: Array): void => {
console.info("**** Observer publish callback ****");
}
dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest", publishCallback);
@@ -711,7 +744,8 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
-let publishedData:Array = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest");
+let dataShareHelper: dataShare.DataShareHelper;
+let publishedData: Promise> = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest");
```
### insert
@@ -733,11 +767,20 @@ Inserts a single data record into the database. This API uses an asynchronous ca
**Example**
```ts
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-const valueBucket = {
- "name": "rose",
- "age": 22,
- "salary": 200.5,
+let key1: string = "name";
+let value1: string = "rose";
+let key2: string = "age";
+let value2: number = 22;
+let key3: string = "salary";
+let value3: number = 200.5;
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
}
try {
dataShareHelper.insert(uri, valueBucket, (err, data) => {
@@ -776,16 +819,26 @@ Inserts a single data record into the database. This API uses a promise to retur
**Example**
```ts
+import { BusinessError } from '@ohos.base'
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-const valueBucket = {
- "name": "rose1",
- "age": 221,
- "salary": 20.5,
+let key1: string = "name";
+let value1: string = "rose1";
+let key2: string = "age";
+let value2: number = 21;
+let key3: string = "salary";
+let value3: number = 20.5;
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
}
try {
- dataShareHelper.insert(uri, valueBucket).then((data) => {
+ dataShareHelper.insert(uri, valueBucket).then((data: number) => {
console.info("insert succeed, data : " + data);
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`insert error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -814,6 +867,7 @@ Deletes one or more data records from the database. This API uses an asynchronou
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
da.equalTo("name", "ZhangSan");
@@ -855,14 +909,16 @@ Deletes one or more data records from the database. This API uses a promise to r
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { BusinessError } from '@ohos.base'
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
da.equalTo("name", "ZhangSan");
try {
- dataShareHelper.delete(uri, da).then((data) => {
+ dataShareHelper.delete(uri, da).then((data: number) => {
console.info("delete succeed, data : " + data);
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`delete error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -892,6 +948,7 @@ Queries data in the database. This API uses an asynchronous callback to return t
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates();
@@ -935,15 +992,17 @@ Queries data in the database. This API uses a promise to return the result.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { BusinessError } from '@ohos.base'
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates();
da.equalTo("name", "ZhangSan");
try {
- dataShareHelper.query(uri, da, columns).then((data) => {
+ dataShareHelper.query(uri, da, columns).then((data: DataShareResultSet) => {
console.info("query succeed, rowCount : " + data.rowCount);
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`query error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -972,15 +1031,22 @@ Updates data in the database. This API uses an asynchronous callback to return t
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
da.equalTo("name", "ZhangSan");
-const va = {
- "name": "roe1",
- "age": 21,
- "salary": 20.5,
-
+let key1: string = "name";
+let value1: string = "roe1"
+let key2: string = "age";
+let value2: number = 21
+let key3: string = "salary";
+let value3: number = 20.5;
+const va: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
}
try {
dataShareHelper.update(uri, da, va, (err, data) => {
@@ -1021,20 +1087,28 @@ Updates data in the database. This API uses a promise to return the result.
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+import { BusinessError } from '@ohos.base'
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
da.equalTo("name", "ZhangSan");
-const va = {
- "name": "roe1",
- "age": 21,
- "salary": 20.5,
-
+let key1: string = "name";
+let value1: string = "roe1"
+let key2: string = "age";
+let value2: number = 21
+let key3: string = "salary";
+let value3: number = 20.5;
+const va: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
}
try {
- dataShareHelper.update(uri, da, va).then((data) => {
+ dataShareHelper.update(uri, da, va).then((data: number) => {
console.info("update succeed, data : " + data);
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`update error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -1061,10 +1135,22 @@ Batch inserts data into the database. This API uses an asynchronous callback to
**Example**
```ts
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
- {"name": "roe12", "age": 21, "salary": 20.5,},
- {"name": "roe13", "age": 21, "salary": 20.5,})
+let key1: string = "name";
+let value11: string = "roe11"
+let key2: string = "age";
+let value21: number = 21;
+let key3: string = "salary";
+let value31: number = 20.5;
+let valuesBucket1: ValuesBucket = {
+ key1: value11,
+ key2: value21,
+ key3: value31,
+}
+let vbs = new Array(valuesBucket1);
try {
dataShareHelper.batchInsert(uri, vbs, (err, data) => {
if (err !== undefined) {
@@ -1102,14 +1188,27 @@ Batch inserts data into the database. This API uses a promise to return the resu
**Example**
```ts
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
- {"name": "roe12", "age": 21, "salary": 20.5,},
- {"name": "roe13", "age": 21, "salary": 20.5,})
+let key1: string = "name";
+let value11: string = "roe11"
+let key2: string = "age";
+let value21: number = 21;
+let key3: string = "salary";
+let value31: number = 20.5;
+let valuesBucket1: ValuesBucket = {
+ key1: value11,
+ key2: value21,
+ key3: value31,
+}
+let vbs = new Array(valuesBucket1);
try {
- dataShareHelper.batchInsert(uri, vbs).then((data) => {
+ dataShareHelper.batchInsert(uri, vbs).then((data: number) => {
console.info("batchInsert succeed, data : " + data);
- }). catch((err) => {
+ }). catch((err: BusinessError) => {
console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `);
});
} catch (err) {
@@ -1135,6 +1234,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.normalizeUri(uri, (err, data) => {
if (err !== undefined) {
@@ -1168,10 +1268,13 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example**
```ts
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-dataShareHelper.normalizeUri(uri).then((data) => {
+dataShareHelper.normalizeUri(uri).then((data: string) => {
console.info("normalizeUri = " + data);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.info("normalizeUri failed, error message : " + err);
});
```
@@ -1194,6 +1297,7 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result.
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.denormalizeUri(uri, (err, data) => {
if (err !== undefined) {
@@ -1227,10 +1331,13 @@ Denormalizes a URI. This API uses a promise to return the result. Silent access
**Example**
```ts
+import { BusinessError } from '@ohos.base'
+
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-dataShareHelper.denormalizeUri(uri).then((data) => {
+dataShareHelper.denormalizeUri(uri).then((data: string) => {
console.info("denormalizeUri = " + data);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error("denormalizeUri failed, error message : " + err);
});
```
@@ -1253,6 +1360,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri, () => {
console.info("***** notifyChange *****");
@@ -1282,6 +1390,7 @@ Notifies the registered observer of data changes. This API uses a promise to ret
**Example**
```ts
+let dataShareHelper: dataShare.DataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri);
```
diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md
index a8188ec8afa535a6d0ba5bc3e2bbd0fb32b8458c..4528a12c607d902868dc6b279f6f9f1bf80843ad 100644
--- a/en/application-dev/reference/apis/js-apis-data-preferences.md
+++ b/en/application-dev/reference/apis/js-apis-data-preferences.md
@@ -49,11 +49,13 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base';
+
let context = featureAbility.getContext();
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
try {
- data_preferences.getPreferences(context, 'mystore', function (err, val) {
+ data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -70,16 +72,18 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base';
+import window from '@ohos.window';
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.getPreferences(this.context, 'mystore', function (err, val) {
+ data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
- console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
- return;
+ console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
+ return;
}
preferences = val;
console.info("Succeeded in getting preferences.");
@@ -119,15 +123,17 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
try {
- let promise = data_preferences.getPreferences(context, 'mystore');
- promise.then((object) => {
+ let promise = data_preferences.getPreferences(context, 'myStore');
+ promise.then((object: data_preferences.Preferences) => {
preferences = object;
console.info("Succeeded in getting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -139,17 +145,19 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- let promise = data_preferences.getPreferences(this.context, 'mystore');
- promise.then((object) => {
+ let promise = data_preferences.getPreferences(this.context, 'myStore');
+ promise.then((object: data_preferences.Preferences) => {
preferences = object;
console.info("Succeeded in getting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -191,11 +199,14 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
try {
- data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.getPreferences(context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -213,13 +224,16 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, val) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -271,15 +285,17 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
try {
- let promise = data_preferences.getPreferences(context, { name: 'mystore' });
- promise.then((object) => {
+ let options: data_preferences.Options = { name: 'myStore' };
+ let promise = data_preferences.getPreferences(context, options);
+ promise.then((object: data_preferences.Preferences) => {
preferences = object;
console.info("Succeeded in getting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -291,17 +307,20 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- let promise = data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' });
- promise.then((object) => {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ let promise = data_preferences.getPreferences(this.context, options);
+ promise.then((object: data_preferences.Preferences) => {
preferences = object;
console.info("Succeeded in getting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -348,11 +367,14 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
-let preferences = null;
+let preferences: data_preferences.Preferences = null;
try {
- preferences = data_preferences.getPreferencesSync(context, { name: 'mystore' });
+ let options: data_preferences.Options = { name: 'myStore' };
+ preferences = data_preferences.getPreferencesSync(context, options);
} catch(err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
@@ -362,12 +384,16 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
-let preferences = null;
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
+
+let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- preferences = data_preferences.getPreferencesSync(this.context, { name: 'mystore', dataGroupId:'myId' });
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ preferences = data_preferences.getPreferencesSync(this.context, options);
} catch(err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
@@ -408,10 +434,12 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- data_preferences.deletePreferences(context, 'mystore', function (err) {
+ data_preferences.deletePreferences(context, 'myStore', (err: BusinessError) => {
if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -427,11 +455,13 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.deletePreferences(this.context, 'mystore', function (err) {
+ data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -483,13 +513,15 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- let promise = data_preferences.deletePreferences(context, 'mystore');
+ let promise = data_preferences.deletePreferences(context, 'myStore');
promise.then(() => {
console.info("Succeeded in deleting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -501,14 +533,16 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try{
- let promise = data_preferences.deletePreferences(this.context, 'mystore');
+ let promise = data_preferences.deletePreferences(this.context, 'myStore');
promise.then(() => {
console.info("Succeeded in deleting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -553,10 +587,13 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- data_preferences.deletePreferences(context, { name: 'mystore' }, function (err) {
+ let options: data_preferences.Options = { name: 'myStore' };
+ data_preferences.deletePreferences(context, options, (err: BusinessError) => {
if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -572,11 +609,14 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.deletePreferences(this.context, options, (err: BusinessError) => {
if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -631,13 +671,16 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- let promise = data_preferences.deletePreferences(context, { name: 'mystore' });
+ let options: data_preferences.Options = { name: 'myStore' };
+ let promise = data_preferences.deletePreferences(context, options);
promise.then(() => {
console.info("Succeeded in deleting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -649,14 +692,17 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try{
- let promise = data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' });
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ let promise = data_preferences.deletePreferences(this.context, options);
promise.then(() => {
console.info("Succeeded in deleting preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -694,9 +740,11 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- data_preferences.removePreferencesFromCache(context, 'mystore', function (err) {
+ data_preferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => {
if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -712,11 +760,13 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
+ data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => {
if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -762,12 +812,14 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
+
let context = featureAbility.getContext();
try {
- let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
+ let promise = data_preferences.removePreferencesFromCache(context, 'myStore');
promise.then(() => {
console.info("Succeeded in removing preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -779,14 +831,16 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore');
+ let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore');
promise.then(() => {
console.info("Succeeded in removing preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -824,7 +878,7 @@ FA model:
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- data_preferences.removePreferencesFromCacheSync(context, 'mystore');
+ data_preferences.removePreferencesFromCacheSync(context, 'myStore');
} catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
@@ -836,9 +890,9 @@ Stage model:
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.removePreferencesFromCacheSync(this.context, 'mystore');
+ data_preferences.removePreferencesFromCacheSync(this.context, 'myStore');
} catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
@@ -882,9 +936,11 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
- data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) {
+ let options: data_preferences.Options = { name: 'myStore' };
+ data_preferences.removePreferencesFromCache(context, options, (err: BusinessError) => {
if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -900,11 +956,14 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -959,12 +1018,14 @@ FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
- let promise = data_preferences.removePreferencesFromCache(context, { name: 'mystore' });
+ let options: data_preferences.Options = { name: 'myStore' };
+ let promise = data_preferences.removePreferencesFromCache(context, options);
promise.then(() => {
console.info("Succeeded in removing preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -976,14 +1037,17 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import { BusinessError } from '@ohos.base'
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- let promise = data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' });
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ let promise = data_preferences.removePreferencesFromCache(this.context, options);
promise.then(() => {
console.info("Succeeded in removing preferences.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -1030,7 +1094,8 @@ FA model:
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
- data_preferences.removePreferencesFromCacheSync(context, { name: 'mystore' });
+ let options: data_preferences.Options = { name: 'myStore' };
+ data_preferences.removePreferencesFromCacheSync(context, options);
} catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
@@ -1040,11 +1105,13 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
try {
- data_preferences.removePreferencesFromCacheSync(this.context, { name: 'mystore', dataGroupId:'myId' });
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.removePreferencesFromCacheSync(this.context, options);
} catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
@@ -1090,7 +1157,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js
try {
- preferences.get('startup', 'default', function (err, val) {
+ preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => {
if (err) {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
return;
@@ -1129,9 +1196,9 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js
try {
let promise = preferences.get('startup', 'default');
- promise.then((data) => {
+ promise.then((data: data_preferences.ValueType) => {
console.info("Got the value of 'startup'. Data: " + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -1164,7 +1231,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js
try {
- let value = preferences.getSync('startup', 'default');
+ let value: data_preferences.ValueType = preferences.getSync('startup', 'default');
console.info("Succeeded in getting value of 'startup'. Data: " + value);
} catch(err) {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
@@ -1189,14 +1256,14 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an
```js
try {
- preferences.getAll(function (err, value) {
+ preferences.getAll((err: BusinessError, value: data_preferences.ValueType) => {
if (err) {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
return;
}
- let allKeys = Object.keys(value);
- console.info("getAll keys = " + allKeys);
- console.info("getAll object = " + JSON.stringify(value));
+ let allKeys = Object.keys(value);
+ console.info("getAll keys = " + allKeys);
+ console.info("getAll object = " + JSON.stringify(value));
})
} catch (err) {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
@@ -1223,11 +1290,11 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses a p
```js
try {
let promise = preferences.getAll();
- promise.then((value) => {
+ promise.then((value: data_preferences.ValueType) => {
let allKeys = Object.keys(value);
console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value));
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
})
} catch (err) {
@@ -1282,7 +1349,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou
```js
try {
- preferences.put('startup', 'auto', function (err) {
+ preferences.put('startup', 'auto', (err: BusinessError) => {
if (err) {
console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
return;
@@ -1323,7 +1390,7 @@ try {
let promise = preferences.put('startup', 'auto');
promise.then(() => {
console.info("Successfully put the value of 'startup'.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
})
} catch(err) {
@@ -1377,7 +1444,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js
try {
- preferences.has('startup', function (err, val) {
+ preferences.has('startup', (err: BusinessError, val: boolean) => {
if (err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
return;
@@ -1387,7 +1454,7 @@ try {
} else {
console.info("The key 'startup' is not contained.");
}
- })
+ })
} catch (err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
@@ -1419,15 +1486,15 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js
try {
let promise = preferences.has('startup');
- promise.then((val) => {
+ promise.then((val: boolean) => {
if (val) {
console.info("The key 'startup' is contained.");
} else {
console.info("The key 'startup' is not contained.");
}
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
- })
+ })
} catch(err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}
@@ -1458,7 +1525,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js
try {
- let isExist = preferences.hasSync('startup');
+ let isExist: boolean = preferences.hasSync('startup');
if (isExist) {
console.info("The key 'startup' is contained.");
} else {
@@ -1489,7 +1556,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie
```js
try {
- preferences.delete('startup', function (err) {
+ preferences.delete('startup', (err: BusinessError) => {
if (err) {
console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
return;
@@ -1529,7 +1596,7 @@ try {
let promise = preferences.delete('startup');
promise.then(() => {
console.info("Deleted the key 'startup'.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
})
} catch(err) {
@@ -1581,7 +1648,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file.
```js
try {
- preferences.flush(function (err) {
+ preferences.flush((err: BusinessError) => {
if (err) {
console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
return;
@@ -1615,7 +1682,7 @@ try {
let promise = preferences.flush();
promise.then(() => {
console.info("Successfully flushed data.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
})
} catch (err) {
@@ -1642,7 +1709,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr
```js
try {
- preferences.clear(function (err) {
+ preferences.clear((err: BusinessError) =>{
if (err) {
console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
return;
@@ -1676,7 +1743,7 @@ try {
let promise = preferences.clear();
promise.then(() => {
console.info("Successfully cleared data.");
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
@@ -1722,29 +1789,31 @@ Subscribes to data changes. A callback will be triggered to return the new value
**Example**
```js
+interface observer {
+ key: string
+}
try {
- data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
+ data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences.");
return;
}
- let observer = function (key) {
+ preferences.on('change', (key: observer) => {
console.info("The key " + key + " changed.");
- }
- preferences.on('change', observer);
- preferences.put('startup', 'manual', function (err) {
+ });
+ preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
- console.error("Failed to put the value of 'startup'. Cause: " + err);
- return;
+ console.error("Failed to put the value of 'startup'. Cause: " + err);
+ return;
}
console.info("Successfully put the value of 'startup'.");
- preferences.flush(function (err) {
- if (err) {
- console.error("Failed to flush. Cause: " + err);
- return;
- }
- console.info("Successfully flushed data.");
+ preferences.flush((err: BusinessError) => {
+ if (err) {
+ console.error("Failed to flush. Cause: " + err);
+ return;
+ }
+ console.info("Successfully flushed data.");
})
})
})
@@ -1781,24 +1850,26 @@ For details about the error codes, see [User Preference Error Codes](../errorcod
**Example 1**
```js
+interface observer {
+ key: string
+}
try {
- data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences.");
return;
}
- let observer = function (key) {
+ preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed.");
- }
- preferences.on('multiProcessChange', observer);
- preferences.put('startup', 'manual', function (err) {
+ });
+ preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
-
- preferences.flush(function (err) {
+ preferences.flush((err: BusinessError) => {
if (err) {
console.error("Failed to flush. Cause: " + err);
return;
@@ -1815,17 +1886,21 @@ try {
**Example 2**
```js
+interface observer {
+ key: string
+}
try {
- data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) {
+ let options: data_preferences.Options = { name: 'myStore' };
+ data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences.");
return;
}
preferences = val;
- let observer = function (key) {
+ preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed.");
try {
- data_preferences.removePreferencesFromCache(this.context, { name: 'mystore' }, function (err) {
+ data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -1838,7 +1913,7 @@ try {
}
try {
- data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) {
+ data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return;
@@ -1849,16 +1924,15 @@ try {
} catch (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}
- }
- preferences.on('multiProcessChange', observer);
- preferences.put('startup', 'manual', function (err) {
+ });
+ preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
- preferences.flush(function (err) {
+ preferences.flush((err: BusinessError) => {
if (err) {
console.error("Failed to flush. Cause: " + err);
return;
@@ -1890,31 +1964,35 @@ Unsubscribes from data changes.
**Example**
```js
+interface observer {
+ key: string
+}
try {
- data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
+ data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences.");
return;
}
- let observer = function (key) {
+ preferences.on('change', (key: observer) => {
console.info("The key " + key + " changed.");
- }
- preferences.on('change', observer);
- preferences.put('startup', 'auto', function (err) {
+ });
+ preferences.put('startup', 'auto', (err: BusinessError) => {
if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
- preferences.flush(function (err) {
+ preferences.flush((err: BusinessError) =>{
if (err) {
console.error("Failed to flush. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
})
- preferences.off('change', observer);
+ preferences.off('change', (key: observer) => {
+ console.info("The key " + key + " changed.");
+ });
})
})
} catch (err) {
@@ -1940,31 +2018,36 @@ Unsubscribes from inter-process data changes.
**Example**
```js
+interface observer {
+ key: string
+}
try {
- data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) {
+ let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
+ data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) {
console.error("Failed to get preferences.");
return;
}
- let observer = function (key) {
+ preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed.");
- }
- preferences.on('multiProcessChange', observer);
- preferences.put('startup', 'auto', function (err) {
+ });
+ preferences.put('startup', 'auto', (err: BusinessError) => {
if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
- preferences.flush(function (err) {
+ preferences.flush((err: BusinessError) => {
if (err) {
console.error("Failed to flush. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
})
- preferences.off('multiProcessChange', observer);
+ preferences.off('multiProcessChange', (key: observer) => {
+ console.info("The key " + key + " changed.");
+ });
})
})
} catch (err) {
diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md
index 8d30126fec7cf31a42a9ae3bacf5d66db8b83238..cc97cf6b3149a5152b232d1771cd3cedfd65acba 100644
--- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md
+++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md
@@ -15,7 +15,7 @@ The **relationalStore** module provides the following functions:
## Modules to Import
```js
-import relationalStore from '@ohos.data.relationalStore'
+import relationalStore from '@ohos.data.relationalStore';
```
## relationalStore.getRdbStore
@@ -52,19 +52,20 @@ FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
+relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
store = rdbStore;
if (err) {
console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
@@ -77,17 +78,19 @@ relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
- var store;
- const STORE_CONFIG = {
+ onWindowStageCreate(windowStage: window.WindowStage) {
+ let store: relationalStore.RdbStore;
+ const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
- relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
+ relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
store = rdbStore;
if (err) {
console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
@@ -137,23 +140,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-let promise = relationalStore.getRdbStore(context, STORE_CONFIG);
-promise.then(async (rdbStore) => {
+let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG);
+promise.then(async (rdbStore: relationalStore.RdbStore) => {
store = rdbStore;
- console.info(`Get RdbStore successfully.`);
-}).catch((err) => {
+ console.info(`Get RdbStore successfully.`)
+}).catch((err: BusinessError) => {
console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -161,21 +165,23 @@ promise.then(async (rdbStore) => {
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
- var store;
- const STORE_CONFIG = {
+ onWindowStageCreate(windowStage: window.WindowStage) {
+ let store: relationalStore.RdbStore;
+ const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-
+
let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG);
- promise.then(async (rdbStore) => {
+ promise.then(async (rdbStore: relationalStore.RdbStore) => {
store = rdbStore;
console.info(`Get RdbStore successfully.`)
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
})
}
@@ -214,14 +220,15 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext()
-relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) {
+relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
@@ -234,13 +241,15 @@ relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) {
+ onWindowStageCreate(windowStage: window.WindowStage){
+ relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
@@ -289,18 +298,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext();
-let promise = relationalStore.deleteRdbStore(context, "RdbTest.db");
+let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db");
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -308,17 +318,19 @@ promise.then(()=>{
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
+ onWindowStageCreate(windowStage: window.WindowStage){
let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db");
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
}
@@ -359,18 +371,19 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext()
-const STORE_CONFIG = {
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) {
+relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
@@ -383,17 +396,19 @@ relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) {
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- const STORE_CONFIG = {
+ onWindowStageCreate(windowStage: window.WindowStage){
+ const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
- relationalStore.deleteRdbStore(this.context, STORE_CONFIG, function (err) {
+ relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
@@ -444,22 +459,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
-import featureAbility from '@ohos.ability.featureAbility'
+import featureAbility from '@ohos.ability.featureAbility';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
// Obtain the context.
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-let promise = relationalStore.deleteRdbStore(context, STORE_CONFIG);
+let promise = relationalStore.deleteRdbStore(this.context, STORE_CONFIG);
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -467,13 +483,15 @@ promise.then(()=>{
Stage model:
```ts
-import UIAbility from '@ohos.app.ability.UIAbility'
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+import { BusinessError } from "@ohos.base";
-var store;
+let store: relationalStore.RdbStore;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- const STORE_CONFIG = {
+ onWindowStageCreate(windowStage: window.WindowStage){
+ const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
@@ -481,7 +499,7 @@ class EntryAbility extends UIAbility {
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
}
@@ -498,7 +516,7 @@ Defines the RDB store configuration.
| ------------- | ------------- | ---- | --------------------------------------------------------- |
| name | string | Yes | Database file name. |
| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. |
-| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store; the value **false** (default) means the opposite.|
+| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store; the value **false** (default) means the opposite.|
| dataGroupId10+ | string | No| Application group ID, which needs to be obtained from the AppGallery.
**Model restriction**: This attribute can be used only in the stage model.
This parameter is supported since API version 10. It specifies the **relationalStore** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **relationalStore** instance is created in the sandbox directory of the application.|
## SecurityLevel
@@ -577,23 +595,25 @@ Defines the data types allowed.
## ValuesBucket
-Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance.
+Enumerates the types of the key in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Key Type| Value Type |
| ------ | ----------------------- |
-| string | [ValueType](#valuetype) |
+| number | The primary key is a number.|
+| string | The primary key is a string.|
## PRIKeyType10+
-Represents the type of the primary key in a row of a database table.
+Enumerates the types of the primary key in a row of a database table.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Type | Description |
| ---------------- | ---------------------------------- |
-| number \| string | The type of the primary key can be number or string.|
+| number | The primary key is a number.|
+| string | The primary key is a string.|
## UTCTime10+
@@ -798,7 +818,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ
> **NOTE**
>
-> The value of **devices** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> The value of **devices** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
+If **inDevices** is specified in **predicates** when **sync()** is called, data is synchronized with the specified device. If **inDevices** is not specified, data is synchronized with all devices on the network by default.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
@@ -817,22 +838,20 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceIds = [];
+import deviceManager from '@ohos.distributedDeviceManager';
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceIds: Array = [];
+
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ for (let i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
+ }
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- for (var i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].deviceId;
- }
-})
-
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.inDevices(deviceIds);
```
@@ -844,6 +863,7 @@ inAllDevices(): RdbPredicates
Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization.
+
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value**
@@ -1639,6 +1659,7 @@ Before using the APIs of this class, use [executeSql](#executesql) to initialize
**Example**
```js
+let store: relationalStore.RdbStore;
// Set the RDB store version.
store.version = 3;
// Obtain the RDB store version.
@@ -1673,13 +1694,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
-store.insert("EMPLOYEE", valueBucket, function (err, rowId) {
+store.insert("EMPLOYEE", valueBucket, (err, rowId) => {
if (err) {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
return;
@@ -1717,13 +1748,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
-store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) {
+store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rowId) => {
if (err) {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
return;
@@ -1765,16 +1806,27 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let promise = store.insert("EMPLOYEE", valueBucket);
-promise.then((rowId) => {
+promise.then((rowId: number) => {
console.info(`Insert is successful, rowId = ${rowId}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -1813,16 +1865,27 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
-promise.then((rowId) => {
+promise.then((rowId: number) => {
console.info(`Insert is successful, rowId = ${rowId}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -1855,27 +1918,45 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket1 = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5])
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+let value5 = "Jack";
+let value6 = 19;
+let value7 = 101.5;
+let value8 = new Uint8Array([6, 7, 8, 9, 10]);
+let value9 = "Tom";
+let value10 = 20;
+let value11 = 102.5;
+let value12 = new Uint8Array([11, 12, 13, 14, 15]);
+const valueBucket1: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
-const valueBucket2 = {
- "NAME": "Jack",
- "AGE": 19,
- "SALARY": 101.5,
- "CODES": new Uint8Array([6, 7, 8, 9, 10])
+const valueBucket2: ValuesBucket = {
+ key1: value5,
+ key2: value6,
+ key3: value7,
+ key4: value8,
};
-const valueBucket3 = {
- "NAME": "Tom",
- "AGE": 20,
- "SALARY": 102.5,
- "CODES": new Uint8Array([11, 12, 13, 14, 15])
+const valueBucket3: ValuesBucket = {
+ key1: value9,
+ key2: value10,
+ key3: value11,
+ key4: value12,
};
let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
-store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) {
+store.batchInsert("EMPLOYEE", valueBuckets, (err, insertNum) => {
if (err) {
console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
return;
@@ -1917,30 +1998,49 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket1 = {
- "NAME": "Lisa",
- "AGE": 18,
- "SALARY": 100.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5])
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Lisa";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+let value5 = "Jack";
+let value6 = 19;
+let value7 = 101.5;
+let value8 = new Uint8Array([6, 7, 8, 9, 10]);
+let value9 = "Tom";
+let value10 = 20;
+let value11 = 102.5;
+let value12 = new Uint8Array([11, 12, 13, 14, 15]);
+const valueBucket1: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
-const valueBucket2 = {
- "NAME": "Jack",
- "AGE": 19,
- "SALARY": 101.5,
- "CODES": new Uint8Array([6, 7, 8, 9, 10])
+const valueBucket2: ValuesBucket = {
+ key1: value5,
+ key2: value6,
+ key3: value7,
+ key4: value8,
};
-const valueBucket3 = {
- "NAME": "Tom",
- "AGE": 20,
- "SALARY": 102.5,
- "CODES": new Uint8Array([11, 12, 13, 14, 15])
+const valueBucket3: ValuesBucket = {
+ key1: value9,
+ key2: value10,
+ key3: value11,
+ key4: value12,
};
let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
let promise = store.batchInsert("EMPLOYEE", valueBuckets);
-promise.then((insertNum) => {
+promise.then((insertNum: number) => {
console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -1973,11 +2073,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
@@ -2019,15 +2129,25 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
-store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) {
+store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => {
if (err) {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2069,18 +2189,29 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
let promise = store.update(valueBucket, predicates);
-promise.then(async (rows) => {
+promise.then(async (rows: Number) => {
console.info(`Updated row count: ${rows}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2119,18 +2250,29 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
let promise = store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
-promise.then(async (rows) => {
+promise.then(async (rows: Number) => {
console.info(`Updated row count: ${rows}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2169,15 +2311,25 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Lisa");
-store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) {
+store.update("EMPLOYEE", valueBucket, predicates, (err, rows) => {
if (err) {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2224,19 +2376,30 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import dataSharePredicates from '@ohos.data.dataSharePredicates'
-const valueBucket = {
- "NAME": "Rose",
- "AGE": 22,
- "SALARY": 200.5,
- "CODES": new Uint8Array([1, 2, 3, 4, 5]),
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+import { BusinessError } from "@ohos.base";
+
+let key1 = "NAME";
+let key2 = "AGE";
+let key3 = "SALARY";
+let key4 = "CODES";
+let value1 = "Rose";
+let value2 = 22;
+let value3 = 200.5;
+let value4 = new Uint8Array([1, 2, 3, 4, 5]);
+const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Lisa");
let promise = store.update("EMPLOYEE", valueBucket, predicates);
-promise.then(async (rows) => {
+promise.then(async (rows: Number) => {
console.info(`Updated row count: ${rows}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2270,7 +2433,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
-store.delete(predicates, function (err, rows) {
+store.delete(predicates, (err, rows) => {
if (err) {
console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2311,12 +2474,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
let promise = store.delete(predicates);
-promise.then((rows) => {
+promise.then((rows: Number) => {
console.info(`Delete rows: ${rows}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2356,7 +2521,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Lisa");
-store.delete("EMPLOYEE", predicates, function (err, rows) {
+store.delete("EMPLOYEE", predicates, (err, rows) => {
if (err) {
console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2402,13 +2567,15 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import dataSharePredicates from '@ohos.data.dataSharePredicates'
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { BusinessError } from "@ohos.base";
+
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Lisa");
let promise = store.delete("EMPLOYEE", predicates);
-promise.then((rows) => {
+promise.then((rows: Number) => {
console.info(`Delete rows: ${rows}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2441,7 +2608,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
-store.query(predicates, function (err, resultSet) {
+store.query(predicates, (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2489,7 +2656,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
-store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) {
+store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2539,11 +2706,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
- ```js
+```js
+import { BusinessError } from "@ohos.base";
+
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
+promise.then((resultSet: relationalStore.ResultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while (resultSet.goToNextRow()) {
@@ -2555,10 +2724,10 @@ promise.then((resultSet) => {
}
// Release the dataset memory.
resultSet.close();
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
- ```
+```
### query10+
@@ -2594,7 +2763,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
-store.query("EMPLOYEE", predicates, function (err, resultSet) {
+store.query("EMPLOYEE", predicates, (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2648,7 +2817,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
-store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) {
+store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2704,11 +2873,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import dataSharePredicates from '@ohos.data.dataSharePredicates'
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { BusinessError } from "@ohos.base";
+
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
+promise.then((resultSet: relationalStore.ResultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while (resultSet.goToNextRow()) {
@@ -2720,7 +2891,7 @@ promise.then((resultSet) => {
}
// Release the dataset memory.
resultSet.close();
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -2733,7 +2904,7 @@ Queries data from the RDB store of a remote device based on specified conditions
> **NOTE**
>
-> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
@@ -2758,41 +2929,38 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceId = null;
+import deviceManager from '@ohos.distributedDeviceManager';
+import { BusinessError } from "@ohos.base";
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- deviceId = devices[0].deviceId;
-})
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceId: string = null;
+
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.greaterThan("id", 0);
-store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
- function(err, resultSet) {
- if (err) {
- console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
- // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
- while (resultSet.goToNextRow()) {
- const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
- const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
- const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
- const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
- console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
- }
- // Release the dataset memory.
- resultSet.close();
+let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
+promise.then((resultSet: relationalStore.ResultSet) => {
+ console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
+ // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
+ while (resultSet.goToNextRow()) {
+ const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
+ const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
+ const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
+ const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
+ console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
-)
+ // Release the dataset memory.
+ resultSet.close();
+}).catch((err: BusinessError) => {
+ console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
+})
```
### remoteQuery
@@ -2803,7 +2971,7 @@ Queries data from the RDB store of a remote device based on specified conditions
> **NOTE**
>
-> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
@@ -2833,24 +3001,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceId = null;
+import deviceManager from '@ohos.distributedDeviceManager';
+import { BusinessError } from "@ohos.base";
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- deviceId = devices[0].deviceId;
-})
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceId: string = null;
+
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.greaterThan("id", 0);
let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
+promise.then((resultSet: relationalStore.ResultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while (resultSet.goToNextRow()) {
@@ -2862,7 +3030,7 @@ promise.then((resultSet) => {
}
// Release the dataset memory.
resultSet.close();
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
})
```
@@ -2893,7 +3061,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", function (err, resultSet) {
+store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2939,7 +3107,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) {
+store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err, resultSet) => {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
@@ -2990,8 +3158,10 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
-promise.then((resultSet) => {
+promise.then((resultSet: relationalStore.ResultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while (resultSet.goToNextRow()) {
@@ -3003,7 +3173,7 @@ promise.then((resultSet) => {
}
// Release the dataset memory.
resultSet.close();
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3036,7 +3206,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
-store.executeSql(SQL_DELETE_TABLE, function(err) {
+store.executeSql(SQL_DELETE_TABLE, (err) => {
if (err) {
console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3074,7 +3244,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?"
-store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) {
+store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err) => {
if (err) {
console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3116,12 +3286,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
let promise = store.executeSql(SQL_DELETE_TABLE);
promise.then(() => {
- console.info(`Delete table done.`);
-}).catch((err) => {
- console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
+ console.info(`Delete table done.`);
+}).catch((err: BusinessError) => {
+ console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3154,12 +3326,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
let PRIKey = [1, 4, 2, 3];
-store.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) {
- if (err) {
- console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
- return;
- }
- let size = modifyTime.size();
+store.getModifyTime("cloud_tasks", "uuid", PRIKey, (err, modifyTime: relationalStore.ModifyTime)=> {
+ if (err) {
+ console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ let size = modifyTime.size;
});
```
@@ -3196,11 +3368,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let PRIKey = [1, 2, 3];
-store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => {
- let size = modifyTime.size();
-}).catch((err) => {
- console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
+store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime: relationalStore.ModifyTime) => {
+ let size = modifyTime.size;
+}).catch((err: BusinessError) => {
+ console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
});
```
@@ -3225,22 +3399,32 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
import featureAbility from '@ohos.ability.featureAbility'
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+let key1 = "name";
+let key2 = "age";
+let key3 = "SALARY";
+let key4 = "blobType";
+let value1 = "Lisi";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3]);
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) {
+relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => {
if (err) {
console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
store.beginTransaction();
- const valueBucket = {
- "name": "lisi",
- "age": 18,
- "salary": 100.5,
- "blobType": new Uint8Array([1, 2, 3]),
+ const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
await store.insert("test", valueBucket);
store.commit();
@@ -3259,22 +3443,32 @@ Commits the executed SQL statements.
```js
import featureAbility from '@ohos.ability.featureAbility'
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+let key1 = "name";
+let key2 = "age";
+let key3 = "SALARY";
+let key4 = "blobType";
+let value1 = "Lisi";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3]);
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) {
+relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => {
if (err) {
console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
store.beginTransaction();
- const valueBucket = {
- "name": "lisi",
- "age": 18,
- "salary": 100.5,
- "blobType": new Uint8Array([1, 2, 3]),
+ const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
};
await store.insert("test", valueBucket);
store.commit();
@@ -3293,25 +3487,34 @@ Rolls back the SQL statements that have been executed.
```js
import featureAbility from '@ohos.ability.featureAbility'
+import { ValuesBucket } from '@ohos.data.ValuesBucket';
+
let context = featureAbility.getContext();
-const STORE_CONFIG = {
+let key1 = "name";
+let key2 = "age";
+let key3 = "SALARY";
+let key4 = "blobType";
+let value1 = "Lisi";
+let value2 = 18;
+let value3 = 100.5;
+let value4 = new Uint8Array([1, 2, 3]);
+const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
-relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) {
+relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => {
if (err) {
console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
try {
store.beginTransaction()
- const valueBucket = {
- "id": 1,
- "name": "lisi",
- "age": 18,
- "salary": 100.5,
- "blobType": new Uint8Array([1, 2, 3]),
- };
+ const valueBucket: ValuesBucket = {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
+ };
await store.insert("test", valueBucket);
store.commit();
} catch (err) {
@@ -3347,7 +3550,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.backup("dbBackup.db", function(err) {
+store.backup("dbBackup.db", (err) => {
if (err) {
console.error(`Backup failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3387,10 +3590,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let promiseBackup = store.backup("dbBackup.db");
promiseBackup.then(()=>{
console.info(`Backup success.`);
-}).catch((err)=>{
+}).catch((err: BusinessError)=>{
console.error(`Backup failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3421,7 +3626,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.restore("dbBackup.db", function(err) {
+store.restore("dbBackup.db", (err) => {
if (err) {
console.error(`Restore failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3461,10 +3666,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let promiseRestore = store.restore("dbBackup.db");
promiseRestore.then(()=>{
console.info(`Restore success.`);
-}).catch((err)=>{
+}).catch((err: BusinessError)=>{
console.error(`Restore failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3497,7 +3704,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.setDistributedTables(["EMPLOYEE"], function (err) {
+store.setDistributedTables(["EMPLOYEE"], (err) => {
if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3539,10 +3746,12 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let promise = store.setDistributedTables(["EMPLOYEE"]);
promise.then(() => {
console.info(`SetDistributedTables successfully.`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3577,7 +3786,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, function (err) {
+store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, (err) => {
if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3619,7 +3828,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
autoSync: true
-}, function (err) {
+},(err) => {
if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3664,12 +3873,14 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
autoSync: true
});
promise.then(() => {
console.info(`SetDistributedTables successfully.`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3682,7 +3893,7 @@ Obtains the distributed table name of a remote device based on the local table n
> **NOTE**
>
-> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
@@ -3707,26 +3918,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceId = null;
+import deviceManager from '@ohos.distributedDeviceManager';
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceId: string = null;
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- deviceId = devices[0].deviceId;
-})
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
-store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) {
- if (err) {
- console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`);
+store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => {
+ if (err) {
+ console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`);
})
```
@@ -3738,7 +3947,7 @@ Obtains the distributed table name of a remote device based on the local table n
> **NOTE**
>
-> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> The value of **device** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
@@ -3768,24 +3977,24 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceId = null;
+import deviceManager from '@ohos.distributedDeviceManager';
+import { BusinessError } from "@ohos.base";
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- deviceId = devices[0].deviceId;
-})
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceId: string = null;
+
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE");
-promise.then((tableName) => {
+promise.then((tableName: string) => {
console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`);
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3819,25 +4028,23 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceIds = [];
+import deviceManager from '@ohos.distributedDeviceManager';
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceIds: Array = [];
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- for (var i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].deviceId;
- }
-})
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ for (let i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
+ }
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.inDevices(deviceIds);
-store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) {
+store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => {
if (err) {
console.error(`Sync failed, code is ${err.code},message is ${err.message}`);
return;
@@ -3883,31 +4090,31 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
-let dmInstance = null;
-let deviceIds = [];
+import deviceManager from '@ohos.distributedDeviceManager';
+import { BusinessError } from "@ohos.base";
-deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.log("create device manager failed, err=" + err);
- return;
- }
- dmInstance = manager;
- let devices = dmInstance.getTrustedDeviceListSync();
- for (var i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].deviceId;
- }
-})
+let dmInstance: deviceManager.DeviceManager = null;
+let deviceIds: Array = [];
+
+try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ for (let i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
+ }
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.inDevices(deviceIds);
let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates);
-promise.then((result) =>{
+promise.then((result: Object[][]) =>{
console.info(`Sync done.`);
for (let i = 0; i < result.length; i++) {
console.info(`device= ${result[i][0]}, status= ${result[i][1]}`);
}
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`Sync failed, code is ${err.code},message is ${err.message}`);
})
```
@@ -3933,14 +4140,14 @@ Manually starts device-cloud synchronization for all distributed tables. This AP
**Example**
```js
-store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
- console.info(`Progess: ${progressDetails}`);
-}, function (err) {
- if (err) {
- console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info('Cloud sync succeeded');
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetails) => {
+ console.info(`Progess: ${progressDetails}`);
+}, (err) =>{
+ if (err) {
+ console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info('Cloud sync succeeded');
});
```
@@ -3970,13 +4177,13 @@ Manually starts device-cloud synchronization for all distributed tables. This AP
**Example**
```js
-function progress(progressDetail) {
- console.info(`progress: ${progressDetail}`);
-}
+import { BusinessError } from "@ohos.base";
-store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => {
+ console.info(`progress: ${progressDetail}`);
+}).then(() => {
console.info('Cloud sync succeeded');
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
});
```
@@ -4004,14 +4211,14 @@ Manually starts device-cloud synchronization of the specified table. This API us
```js
const tables = ["table1", "table2"];
-store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
- console.info(`Progess: ${progressDetails}`);
-}, function (err) {
- if (err) {
- console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info('Cloud sync succeeded');
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, (progressDetail: relationalStore.ProgressDetails) => {
+ console.info(`Progess: ${progressDetails}`);
+}, (err) => {
+ if (err) {
+ console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info('Cloud sync succeeded');
});
```
@@ -4042,14 +4249,15 @@ Manually starts device-cloud synchronization of the specified table. This API us
**Example**
```js
+import { BusinessError } from "@ohos.base";
+
const tables = ["table1", "table2"];
-function progress(progressDetail) {
- console.info(`progress: ${progressDetail}`);
-}
-store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
+store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => {
+ console.info(`progress: ${progressDetail}`);
+}).then(() => {
console.info('Cloud sync succeeded');
-}).catch((err) => {
+}).catch((err: BusinessError) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
});
```
@@ -4073,13 +4281,15 @@ Registers a data change event listener for the RDB store. When the data in the R
**Example**
```js
-function storeObserver(devices) {
- for (let i = 0; i < devices.length; i++) {
- console.info(`device= ${devices[i]} data changed`);
- }
-}
+import deviceManager from '@ohos.distributedHardware.deviceManager';
try {
- store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver);
+ store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => {
+ let devices: string;
+ for (let i = 0; i < devices.length; i++) {
+ console.info(`device= ${devices[i]} data changed`);
+ }
+ }
+ );
} catch (err) {
console.error(`Register observer failed, code is ${err.code},message is ${err.message}`);
}
@@ -4104,6 +4314,7 @@ Registers a data change event listener for the RDB store. When the data in the R
**Example**
```js
+import deviceManager from '@ohos.distributedHardware.deviceManager';
function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) {
console.info(`device= ${devices[i]} data changed`);
@@ -4129,7 +4340,7 @@ Registers an intra-process or inter-process event listener for the RDB store. Th
| Name | Type | Mandatory| Description |
| ------------ | --------------- | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event name to observe. |
-| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event. |
+| interProcess | boolean | Yes | Type of the event to observe.
The value **true** means the inter-process event.
The value **false** means the intra-process event.|
| observer | Callback\ | Yes | Callback invoked to return the result. |
**Error codes**
@@ -4144,11 +4355,10 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-function storeObserver() {
- console.info(`storeObserver`);
-}
try {
- store.on('storeObserver', false, storeObserver);
+ store.on('storeObserver', false, (storeObserver) => {
+ console.info(`storeObserver`);
+ });
} catch (err) {
console.error(`Register observer failed, code is ${err.code},message is ${err.message}`);
}
@@ -4173,13 +4383,15 @@ Unregisters the data change event listener.
**Example**
```
-function storeObserver(devices) {
- for (let i = 0; i < devices.length; i++) {
- console.info(`device= ${devices[i]} data changed`);
- }
-}
+import deviceManager from '@ohos.distributedHardware.deviceManager';
try {
- store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver);
+ store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => {
+ let devices: string;
+ for (let i = 0; i < devices.length; i++) {
+ console.info(`device= ${devices[i]} data changed`);
+ }
+ }
+ );
} catch (err) {
console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`);
}
@@ -4204,13 +4416,15 @@ Unregisters the data change event listener.
**Example**
```js
-function storeObserver(devices) {
- for (let i = 0; i < devices.length; i++) {
- console.info(`device= ${devices[i]} data changed`);
- }
-}
+import deviceManager from '@ohos.distributedHardware.deviceManager';
try {
- store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver);
+ store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => {
+ let devices: string;
+ for (let i = 0; i < devices.length; i++) {
+ console.info(`device= ${devices[i]} data changed`);
+ }
+ }
+ );
} catch (err) {
console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`);
}
@@ -4244,11 +4458,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-function storeObserver() {
- console.info(`storeObserver`);
-}
try {
- store.off('storeObserver', false, storeObserver);
+ store.off('storeObserver', false, (storeObserver) => {
+ console.info(`storeObserver`);
+ }
+ );
} catch (err) {
console.error(`Register observer failed, code is ${err.code},message is ${err.message}`);
}
@@ -4292,11 +4506,11 @@ Provides APIs to access the result set obtained by querying the RDB store. A res
Obtain the **resultSet** object first.
```js
-let resultSet = null;
+let resultSet: relationalStore.ResultSet = null;
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("AGE", 18);
let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((result) => {
+promise.then((result: relationalStore.ResultSet) => {
resultSet = result;
console.info(`resultSet columnNames: ${resultSet.columnNames}`);
console.info(`resultSet columnCount: ${resultSet.columnCount}`);
@@ -4350,7 +4564,6 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-resultSet.goToFirstRow();
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
@@ -4424,14 +4637,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise= store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goTo(1);
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### goToRow
@@ -4465,14 +4671,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goToRow(5);
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### goToFirstRow
@@ -4501,14 +4700,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goToFirstRow();
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### goToLastRow
@@ -4536,14 +4728,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goToLastRow();
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### goToNextRow
@@ -4571,14 +4756,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goToNextRow();
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### goToPreviousRow
@@ -4606,14 +4784,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
**Example**
```js
-let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
-let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSet) => {
resultSet.goToPreviousRow();
- resultSet.close();
-}).catch((err) => {
- console.error(`query failed, code is ${err.code},message is ${err.message}`);
-});
```
### getBlob
@@ -4866,13 +5037,7 @@ Closes this result set.
**Example**
```js
-let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE");
-let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promiseClose.then((resultSet) => {
resultSet.close();
-}).catch((err) => {
- console.error(`resultset close failed, code is ${err.code},message is ${err.message}`);
-});
```
**Error codes**
diff --git a/en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md b/en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md
new file mode 100644
index 0000000000000000000000000000000000000000..e75ea7e1ccc4b2439a953512b59f8b07e1147927
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md
@@ -0,0 +1,875 @@
+# @ohos.data.unifiedDataChannel (Unified Data Channel)
+
+As a part of the Unified Data Management Framework (UDMF), the **unifiedDataChannel** module provides unified data channels and standard data access interfaces for many-to-many data sharing across applications. It also provides standard definitions for data types, such as text and image, to streamline data interaction between different applications and minimize the workload of data type adaptation.
+
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+## Modules to Import
+
+```js
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+```
+
+## UnifiedData
+
+Provides APIs for encapsulating a set of data records.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+### constructor
+
+constructor(record: UnifiedRecord)
+
+A constructor used to create a **UnifiedData** object with a data record.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------------------------------- | ---- |-----------------------------------------|
+| record | [UnifiedRecord](#unifiedrecord) | Yes | Data record in the **UnifiedData** object. It is a **UnifiedRecord** child class object.|
+
+**Example**
+
+```js
+let text = new unifiedDataChannel.PlainText();
+text.textContent = 'this is textContent of text';
+let unifiedData = new unifiedDataChannel.UnifiedData(text);
+```
+
+### addRecord
+
+addRecord(record: UnifiedRecord): void
+
+Adds a data record to this **UnifiedRecord** object.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------------------------------- | ---- |---------------------------------------------|
+| record | [UnifiedRecord](#unifiedrecord) | Yes | Data record to add. It is a **UnifiedRecord** child class object.|
+
+**Example**
+
+```js
+let text1 = new unifiedDataChannel.PlainText();
+text1.textContent = 'this is textContent of text1';
+let unifiedData = new unifiedDataChannel.UnifiedData(text1);
+
+let text2 = new unifiedDataChannel.PlainText();
+text2.textContent = 'this is textContent of text2';
+unifiedData.addRecord(text2);
+```
+
+### getRecords
+
+getRecords(): Array\
+
+Obtains all data records from this **UnifiedData** object. The data obtained is of the **UnifiedRecord** type. Before using the data, you need to use [getType](#gettype) to obtain the data type and convert the data type to a child class.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- |-------------------------|
+| Array\<[UnifiedRecord](#unifiedrecord)\> | Records in the **UnifiedData** object obtained.|
+
+**Example**
+
+```js
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+
+let text = new unifiedDataChannel.PlainText();
+text.textContent = 'this is textContent of text';
+let unifiedData = new unifiedDataChannel.UnifiedData(text);
+
+let link = new unifiedDataChannel.Hyperlink();
+link.url = 'www.XXX.com';
+unifiedData.addRecord(link);
+
+let records = unifiedData.getRecords();
+for (let i = 0; i < records.length; i++) {
+ let record = records[i];
+ if (record.getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let plainText = record as unifiedDataChannel.PlainText;
+ console.info(`textContent: ${plainText.textContent}`);
+ } else if (record.getType() == uniformTypeDescriptor.UniformDataType.HYPERLINK) {
+ let hyperlink = record as unifiedDataChannel.Hyperlink;
+ console.info(`linkUrl: ${hyperlink.url}`);
+ }
+}
+```
+
+## Summary
+
+Defines the summary of a **UnifiedData object**, including the data types and sizes. Currently, it is not supported.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| --------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------|
+| summary | { [key: string]: number } | Yes | No | Dictionary type object, where the key indicates the data type (see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype)), and the value indicates the total size (in bytes) of this type of records in the **UnifiedData** object.|
+| totalSize | number | Yes | No | Total size of all the records in the **UnifiedData** object, in bytes. |
+
+## UnifiedRecord
+
+An abstract definition of the data content supported by the UDMF. A **UnifiedRecord** object contains one or more data records, for example, a text record, an image record, or an HTML record.
+
+**UnifiedRecord** is an abstract parent class that does not hold specific data content. It cannot be added to a **UnifiedData** object directly. Instead, a child class with specific content, such as text and image, must be created.
+
+### getType
+
+getType(): string
+
+Obtains the type of this **UnfiedRecord**. The data obtained by [getRecords](#getrecords) from the **UnifiedData** object is a **UnifiedRecord** object. You need to use this API to obtain the specific type of the record, convert the **UnifiedRecord** object to its child class, and call the child class interfaces.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Return value**
+
+| Type | Description |
+| ------ |------------------------------------------------------|
+| string | Data type obtained. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype).|
+
+**Example**
+
+```js
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+
+let text = new unifiedDataChannel.PlainText();
+text.textContent = 'this is textContent of text';
+let unifiedData = new unifiedDataChannel.UnifiedData(text);
+
+let records = unifiedData.getRecords();
+if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let plainText = records[0] as unifiedDataChannel.PlainText;
+ console.info(`textContent: ${plainText.textContent}`);
+}
+```
+
+## Text
+
+Represents the text data. It is a child class of [UnifiedRecord](#unifiedrecord) and a base class of text data. You are advised to use the child class of **Text**, for example, [PlainText](#plaintext), [Hyperlink](#hyperlink), and [HTML](#html), to describe data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------------------------------------------------------------------------|
+| details | { [key: string]: string } | Yes | Yes | A dictionary type object, where both the key and value are of the string type and are used to describe the text content. For example, a data object with the following content can be created to describe a text file:
{
"title":"Title",
"content":"Content"
}
This parameter is optional. The default value is an empty dictionary object.|
+
+**Example**
+
+```js
+let text = new unifiedDataChannel.Text();
+text.details = {
+ title: 'MyTitle',
+ content: 'this is content',
+};
+let unifiedData = new unifiedDataChannel.UnifiedData(text);
+```
+
+## PlainText
+
+Represents the plaintext data. It is a child class of [Text](#text) and is used to describe plaintext data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------- | ------ | ---- | ---- |-----------------------|
+| textContent | string | Yes | Yes | Plaintext content. |
+| abstract | string | Yes | Yes | Text abstract. This parameter is optional. The default value is an empty string.|
+
+**Example**
+
+```js
+let text = new unifiedDataChannel.PlainText();
+text.textContent = 'this is textContent';
+text.abstract = 'this is abstract';
+```
+
+## Hyperlink
+
+Represents hyperlink data. It is a child class of [Text](#text) and is used to describe data of the hyperlink type.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------- | ------ | ---- | ---- |--------------|
+| url | string | Yes | Yes | URL. |
+| description | string | Yes | Yes | Description of the linked content. This parameter is optional. The default value is an empty string.|
+
+**Example**
+
+```js
+let link = new unifiedDataChannel.Hyperlink();
+link.url = 'www.XXX.com';
+link.description = 'this is description';
+```
+
+## HTML
+
+Represents the HTML data. It is a child class of [Text](#text) and is used to describe HTML data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ------------ | ------ | ---- | ---- |-----------------------|
+| htmlContent | string | Yes | Yes | Content in HTML format. |
+| plainContent | string | Yes | Yes | Plaintext without HTML tags. This parameter is optional. The default value is an empty string.|
+
+**Example**
+
+```js
+let html = new unifiedDataChannel.HTML();
+html.htmlContent = '';
+html.plainContent = 'this is plainContent';
+```
+
+## File
+
+Represents the file data. It is a child class of [UnifiedRecord](#unifiedrecord) and a base class of the data of the file type. You are advised to use the child class of **File**, for example, [Image](#image), [Video](#video), and [Folder](#folder), to describe data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+|---------|---------------------------| ---- | ---- |------------------------------------------------------------------------------------------------------------------------------------------------------|
+| details | { [key: string]: string } | Yes | Yes | A dictionary type object, where both the key and value are of the string type and are used to describe file information. For example, a data object with the following content can be created to describe a file:
{
"name":"File name",
"type":"File type"
}
This parameter is optional. The default value is an empty dictionary object.|
+| uri | string | Yes | Yes | URI of the file data. |
+
+**Example**
+
+```js
+let file = new unifiedDataChannel.File();
+file.details = {
+ name: 'test',
+ type: 'txt',
+};
+file.uri = 'schema://com.samples.test/files/test.txt';
+```
+
+## Image
+
+Represents the image data. It is a child class of [File](#file) and is used to describe images.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| -------- | ------ | ---- | ---- |----------|
+| imageUri | string | Yes | Yes | URI of the image.|
+
+**Example**
+
+```js
+let image = new unifiedDataChannel.Image();
+image.imageUri = 'schema://com.samples.test/files/test.jpg';
+```
+
+## Video
+
+Represents video data. It is a child class of [File](#file) and is used to describe a video file.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| -------- | ------ | ---- | ---- |----------|
+| videoUri | string | Yes | Yes | URI of the video file.|
+
+**Example**
+
+```js
+let video = new unifiedDataChannel.Video();
+video.videoUri = 'schema://com.samples.test/files/test.mp4';
+```
+
+## Audio
+
+Represents video data. It is a child class of [File](#file) and is used to describe a video file.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+|----------|--------|----|----|----------|
+| audioUri | string | Yes | Yes | Audio data URI.|
+
+**Example**
+
+```js
+let audio = new unifiedDataChannel.Audio();
+audio.audioUri = 'schema://com.samples.test/files/test.mp3';
+```
+
+## Folder
+
+Represents the folder data. It is a child class of [File](#file) and is used to describe a folder.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| -------- | ------ | ---- | ---- |---------|
+| folderUri | string | Yes | Yes | URI of the folder.|
+
+**Example**
+
+```js
+let folder = new unifiedDataChannel.Folder();
+folder.folderUri = 'schema://com.samples.test/files/folder/';
+```
+
+## SystemDefinedRecord
+
+Represents specific data types defined by OpenHarmony. It is a child class of [UnifiedRecord](#unifiedrecord) and a base class of OpenHarmony-specific data types. You are advised to use the child class of **SystemDefinedRecord**, for example, [SystemDefinedForm](#systemdefinedform), [SystemDefinedAppItem](#systemdefinedappitem), and [SystemDefinedPixelMap](#systemdefinedpixelmap), to describe OpenHarmony-specific data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ------- |--------------------------| ---- | ---- | ------------------------------------------------------------ |
+| details | { [key: string]: number \| string \| Uint8Array } | Yes | Yes | A dictionary type object, where the key is of the string type, and the value can be a number, a string, or a Uint8Array.
This parameter is optional. The default value is an empty dictionary object.|
+
+**Example**
+
+```js
+let sdr = new unifiedDataChannel.SystemDefinedRecord();
+let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+sdr.details = {
+ title: 'recordTitle',
+ version: 1,
+ content: u8Array,
+};
+let unifiedData = new unifiedDataChannel.UnifiedData(sdr);
+```
+
+## SystemDefinedForm
+
+Represents the widget data. It is a child class of [SystemDefinedRecord](#systemdefinedrecord).
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------- | ------ | ---- | ---- |----------------|
+| formId | number | Yes | Yes | Service widget ID. |
+| formName | string | Yes | Yes | Widget name. |
+| bundleName | string | Yes | Yes | Name of the bundle to which a widget belongs. |
+| abilityName | string | Yes | Yes | Ability name corresponding to the widget.|
+| module | string | Yes | Yes | Name of the module to which the widget belongs. |
+
+**Example**
+
+```js
+let form = new unifiedDataChannel.SystemDefinedForm();
+form.formId = 123456;
+form.formName = 'MyFormName';
+form.bundleName = 'MyBundleName';
+form.abilityName = 'MyAbilityName';
+form.module = 'MyModule';
+let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+form.details = {
+ formKey1: 123,
+ formKey2: 'formValue',
+ formKey3: u8Array,
+};
+let unifiedData = new unifiedDataChannel.UnifiedData(form);
+```
+
+## SystemDefinedAppItem
+
+Represents the icon data. It is a child class of [SystemDefinedRecord](#systemdefinedrecord).
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------- | ------ | ---- | ---- |-----------------|
+| appId | string | Yes | Yes | ID of the application, for which the icon is used. |
+| appName | string | Yes | Yes | Name of the application, for which the icon is used. |
+| appIconId | string | Yes | Yes | Image ID of the icon. |
+| appLabelId | string | Yes | Yes | Label ID corresponding to the icon name. |
+| bundleName | string | Yes | Yes | Bundle name corresponding to the icon.|
+| abilityName | string | Yes | Yes | Application ability name corresponding to the icon.|
+
+**Example**
+
+```js
+let appItem = new unifiedDataChannel.SystemDefinedAppItem();
+appItem.appId = 'MyAppId';
+appItem.appName = 'MyAppName';
+appItem.appIconId = 'MyAppIconId';
+appItem.appLabelId = 'MyAppLabelId';
+appItem.bundleName = 'MyBundleName';
+appItem.abilityName = 'MyAbilityName';
+let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+appItem.details = {
+ appItemKey1: 123,
+ appItemKey2: 'appItemValue',
+ appItemKey3: u8Array,
+};
+let unifiedData = new unifiedDataChannel.UnifiedData(appItem);
+```
+
+## SystemDefinedPixelMap
+
+Represents the image data corresponding to the [PixelMap](js-apis-image.md#pixelmap7) defined by OpenHarmony. It is a child class of [SystemDefinedRecord](#systemdefinedrecord) and used to store only the binary data of **PixelMap**.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ---------- | ---- | ---- |-------------------|
+| rawData | Uint8Array | Yes | Yes | Binary data of the **PixelMap** object.|
+
+**Example**
+
+```js
+import image from '@ohos.multimedia.image'; // Module where the PixelMap class is defined.
+
+const color = new ArrayBuffer(96); // Create a PixelMap object.
+let opts: image.InitializationOptions = {
+ editable: true, pixelFormat: 3, size: {
+ height: 4, width: 6
+ }
+}
+image.createPixelMap(color, opts, (error, pixelmap) => {
+ if (error) {
+ console.error('Failed to create pixelmap.');
+ } else {
+ console.info('Succeeded in creating pixelmap.');
+ let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber());
+ pixelmap.readPixelsToBuffer(arrayBuf);
+ let u8Array = new Uint8Array(arrayBuf);
+ let sdpixel = new unifiedDataChannel.SystemDefinedPixelMap();
+ sdpixel.rawData = u8Array;
+ let unifiedData = new unifiedDataChannel.UnifiedData(sdpixel);
+ }
+})
+```
+
+## ApplicationDefinedRecord
+
+Represents the custom data type for applications only. It is a child class of [UnifiedRecord](#unifiedrecord) and a base class of custom data types of applications. Applications can extend custom data types based on this class.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Type | Readable| Writable| Description |
+|------------------------|------------| ---- | ---- |---------------------------------------|
+| applicationDefinedType | string | Yes | Yes | Application's custom data type identifier, which must start with **ApplicationDefined**.|
+| rawData | Uint8Array | Yes | Yes | Binary data of the custom data type. |
+
+**Example**
+
+```js
+let record = new unifiedDataChannel.ApplicationDefinedRecord();
+let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+record.applicationDefinedType = 'ApplicationDefinedType';
+record.rawData = u8Array;
+let unifiedData = new unifiedDataChannel.UnifiedData(record);
+```
+
+## Intention
+
+Enumerates the data channel types supported by the UDMF. It is used to identify different service scenarios, to which the UDMF data channels apply.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Value | Description |
+|----------|-----------|---------|
+| DATA_HUB | 'DataHub' | Public data channel.|
+
+## Options
+
+Defines the data operation performed by the UDMF. It includes two optional parameters: **intention** and **key**. The two parameters have no default value, and can be left unspecified. For details, see the parameter description of the specific API.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+
+| Name | Type | Readable| Writable| Mandatory| Description |
+|-----------|-------------------------|----|----|----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| intention | [Intention](#intention) | Yes | Yes | No | Type of the data channel related to the data operation. |
+| key | string | Yes | Yes | No | Unique identifier of the data object in the UDMF, which can be obtained from the value returned by [insertData](#unifieddatachannelinsertdata).
The key consists of **udmf:/**, **intention**, **bundleName**, and **groupId** with a (/) in between, for example, **udmf://DataHub/com.ohos.test/0123456789**.
**udmf:/** is fixed, **DataHub** is an enum of **intention**, **com.ohos.test** is the bundle name, and **0123456789** is a group ID randomly generated.|
+
+
+
+## unifiedDataChannel.insertData
+
+insertData(options: Options, data: UnifiedData, callback: AsyncCallback<string>): void
+
+Inserts data to the UDMF public data channel. This API uses an asynchronous callback to return the unique identifier of the data inserted.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|----------|----------------------------|----|------------------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Only the **intention** is required. |
+| data | [UnifiedData](#unifieddata) | Yes | Data to insert. |
+| callback | AsyncCallback<string> | Yes | Callback invoked to return the key (unique identifier) of the data inserted.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import { BusinessError } from '@ohos.base';
+
+let plainText = new unifiedDataChannel.PlainText();
+plainText.textContent = 'hello world!';
+let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
+
+let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
+}
+try {
+ unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in inserting data. key = ${data}`);
+ } else {
+ console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+ } catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+
+```
+
+## unifiedDataChannel.insertData
+
+insertData(options: Options, data: UnifiedData): Promise<string>
+
+Inserts data to the UDMF public data channel. This API uses a promise to return the unique identifier of the data inserted.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|---------|-----------------------------|----|-----------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Only the **intention** is required.|
+| data | [UnifiedData](#unifieddata) | Yes | Data to insert. |
+
+**Return value**
+
+| Type | Description |
+|-----------------------|-----------------------------------|
+| Promise<string> | Promise used to return the key of the data inserted.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import { BusinessError } from '@ohos.base';
+
+let plainText = new unifiedDataChannel.PlainText();
+plainText.textContent = 'hello world!';
+let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
+
+let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
+}
+try {
+ unifiedDataChannel.insertData(options, unifiedData).then((data) => {
+ console.info(`Succeeded in inserting data. key = ${data}`);
+ }).catch((err: BusinessError) => {
+ console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.updateData
+
+updateData(options: Options, data: UnifiedData, callback: AsyncCallback<void>): void
+
+Updates the data in the UDMF public data channel. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|----------|-----------------------------|----|-------------------------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Only the value of **key** is required. |
+| data | [UnifiedData](#unifieddata) | Yes | New data. |
+| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is updated successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import { BusinessError } from '@ohos.base';
+
+let plainText = new unifiedDataChannel.PlainText();
+plainText.textContent = 'hello world!';
+let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
+
+let options: unifiedDataChannel.Options = {
+ key: 'udmf://DataHub/com.ohos.test/0123456789'
+};
+
+try {
+ unifiedDataChannel.updateData(options, unifiedData, (err) => {
+ if (err === undefined) {
+ console.info('Succeeded in updating data.');
+ } else {
+ console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.updateData
+
+updateData(options: Options, data: UnifiedData): Promise<void>
+
+Updates the data in the UDMF public data channel. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|---------|-----------------------------|----|-----------------|
+| options | [Options](#options) | Yes | Configuration parameters. Only the value of **key** is required.|
+| data | [UnifiedData](#unifieddata) | Yes | New data. |
+
+**Return value**
+
+| Type | Description |
+|---------------------|----------------------------|
+| Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import { BusinessError } from '@ohos.base';
+
+let plainText = new unifiedDataChannel.PlainText();
+plainText.textContent = 'hello world!';
+let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
+
+let options: unifiedDataChannel.Options = {
+ key: 'udmf://DataHub/com.ohos.test/0123456789'
+};
+
+try {
+ unifiedDataChannel.updateData(options, unifiedData).then(() => {
+ console.info('Succeeded in updating data.');
+ }).catch((err: BusinessError) => {
+ console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.queryData
+
+queryData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void
+
+Queries data in the UDMF public data channel. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|----------|---------------------------------------------------------------|----|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Both the **key** and **intention** are optional, and the return value varies depending on the parameters passed in. |
+| callback | AsyncCallback<Array<[UnifiedData](#unifieddata)>> | Yes | Callback invoked to return the queried data.
If only the **key** is specified in **options**, the data corresponding to the key is returned.
If only the **intention** is specified in **options**, all data in the **intention** is returned.
If both **intention** and **key** are specified, the intersection of the two is returned, which is the result obtained when only **key** is specified. If there is no intersection between the specified **intention** and **key**, an error object is returned.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+import { BusinessError } from '@ohos.base';
+
+let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
+};
+
+try {
+ unifiedDataChannel.queryData(options, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in querying data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
+ }
+ }
+ } else {
+ console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.queryData
+
+queryData(options: Options): Promise<Array<UnifiedData>>
+
+Queries data in the UDMF public data channel. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|---------|---------------------|----|-----------------------------------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Both the **key** and **intention** are optional, and the return value varies depending on the parameters passed in.|
+
+**Return value**
+
+| Type | Description |
+|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
+| Promise<Array<[UnifiedData](#unifieddata)>> | Promise used to return the result.
If only the **key** is specified in **options**, the data corresponding to the key is returned.
If only the **intention** is specified in **options**, all data in the **intention** is returned.
If both **intention** and **key** are specified, the intersection of the two is returned, which is the result obtained when only **key** is specified. If there is no intersection between the specified **intention** and **key**, an error object is returned.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+import { BusinessError } from '@ohos.base';
+
+let options: unifiedDataChannel.Options = {
+ key: 'udmf://DataHub/com.ohos.test/0123456789'
+};
+
+try {
+ unifiedDataChannel.queryData(options).then((data) => {
+ console.info(`Succeeded in querying data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
+ }
+ }
+ }).catch((err: BusinessError) => {
+ console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.deleteData
+
+deleteData(options: Options, callback: AsyncCallback<Array<UnifiedData>>): void
+
+Deletes data from the UDMF public data channel. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|----------|---------------------------------------------------------------|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| options | [Options](#options) | Yes | Configuration parameters. Both the **key** and **intention** are optional, and the return value varies depending on the parameters passed in. |
+| callback | AsyncCallback<Array<[UnifiedData](#unifieddata)>> | Yes | Callback invoked to return the data deleted.
If only the **key** is specified in **options**, the data corresponding to the key deleted is returned.
If only the **intention** is specified in **options**, all data in the **intention** deleted is returned.
If both **intention** and **key** are specified, the intersection of the two deleted is returned. If there is no intersection between the two, an error object is returned.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+import { BusinessError } from '@ohos.base';
+
+let options: unifiedDataChannel.Options = {
+ intention: unifiedDataChannel.Intention.DATA_HUB
+};
+
+try {
+ unifiedDataChannel.deleteData(options, (err, data) => {
+ if (err === undefined) {
+ console.info(`Succeeded in deleting data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
+ }
+ }
+ } else {
+ console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
+ }
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
+
+## unifiedDataChannel.deleteData
+
+deleteData(options: Options): Promise<Array<UnifiedData>>
+
+Deletes data from the UDMF public data channel. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|---------|---------------------|----|--------|
+| options | [Options](#options) | Yes | Configuration parameters. Both the **key** and **intention** are optional, and the return value varies depending on the parameters passed in.|
+
+**Return value**
+
+| Type | Description |
+|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Promise<Array<[UnifiedData](#unifieddata)>> | Promise used to return the data deleted.
If only the **key** is specified in **options**, the data corresponding to the key deleted is returned.
If only the **intention** is specified in **options**, all data in the **intention** deleted is returned.
If both **intention** and **key** are specified, the intersection of the two deleted is returned. If there is no intersection between the two, an error object is returned.|
+
+**Example**
+
+```ts
+import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+import { BusinessError } from '@ohos.base';
+
+let options: unifiedDataChannel.Options = {
+ key: 'udmf://DataHub/com.ohos.test/0123456789'
+};
+
+try {
+ unifiedDataChannel.deleteData(options).then((data) => {
+ console.info(`Succeeded in deleting data. size = ${data.length}`);
+ for (let i = 0; i < data.length; i++) {
+ let records = data[i].getRecords();
+ for (let j = 0; j < records.length; j++) {
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = records[j] as unifiedDataChannel.PlainText;
+ console.info(`${i + 1}.${text.textContent}`);
+ }
+ }
+ }
+ }).catch((err: BusinessError) => {
+ console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
+ });
+} catch (e) {
+ let error: BusinessError = e as BusinessError;
+ console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md b/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md
new file mode 100644
index 0000000000000000000000000000000000000000..edf2e5ac34b0785ffe2c5076badfabc80221d2b5
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md
@@ -0,0 +1,34 @@
+# @ohos.data.uniformTypeDescriptor (Standard Data Definition)
+
+The **uniformTypeDescriptor** module provides abstract definitions of OpenHarmony standardized data types.
+
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+## Modules to Import
+
+```js
+import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
+```
+
+## UniformDataType
+
+Enumerates the types of OpenHarmony standard data.
+
+**System capability**: SystemCapability.DistributedDataManager.UDMF.Core
+
+| Name | Value | Description |
+|----------------------------|------------------------------|-----------|
+| TEXT | 'general.text' | Text. |
+| PLAIN_TEXT | 'general.plain-text' | Plaintext. |
+| HYPERLINK | 'general.hyperlink' | Hyperlink. |
+| HTML | 'general.html' | HyperText Markup Language (HTML). |
+| FILE | 'general.file' | File. |
+| IMAGE | 'general.image' | Image. |
+| VIDEO | 'general.video' | Video. |
+| AUDIO | 'general.audio' | Audio. |
+| FOLDER | 'general.folder' | Folder. |
+| OPENHARMONY_FORM | 'openharmony.form' | Widget. |
+| OPENHARMONY_APP_ITEM | 'openharmony.app-item' | Icon. |
+| OPENHARMONY_PIXEL_MAP | 'openharmony.pixel-map' | Pixel map. |
diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md
index 6cde0cf71b73660bf168b36feac2805753f08b79..2a4e91e3d798268e945744cf2c3d90755357dd32 100644
--- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md
+++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md
@@ -12,8 +12,7 @@ The **distributedKVStore** module provides the following functions:
> **NOTE**
>
-> - 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.
-> - All the APIs that need to obtain **deviceId** in this module are available only to system applications.
+> 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.
## Modules to Import
@@ -2030,7 +2029,7 @@ deviceId(deviceId:string):Query
Creates a **Query** object with the device ID as the key prefix.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
@@ -2819,7 +2818,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void
Deletes data of a device. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -2871,7 +2870,7 @@ removeDeviceData(deviceId: string): Promise<void>
Deletes data of a device. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -4550,7 +4549,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE**
>
-> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
@@ -4576,40 +4575,41 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
+import deviceManager from '@ohos.distributedDeviceManager';
let devManager;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager
-deviceManager.createDeviceManager('bundleName', (err, value) => {
- if (!err) {
- devManager = value;
- let deviceIds = [];
- if (devManager != null) {
- var devices = devManager.getTrustedDeviceListSync();
- for (var i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].networkId;
- }
- }
- try {
- kvStore.on('syncComplete', function (data) {
- console.info('Sync dataChange');
- });
- kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) {
- if (err != undefined) {
- console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info('Succeeded in putting data');
- const mode = distributedKVStore.SyncMode.PULL_ONLY;
- kvStore.sync(deviceIds, mode, 1000);
- });
- } catch (e) {
- console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
+try {
+ devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
+ let deviceIds = [];
+ if (devManager != null) {
+ var devices = devManager.getAvailableDeviceListSync();
+ for (var i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
}
}
-});
+ try {
+ kvStore.on('syncComplete', function (data) {
+ console.info('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) {
+ if (err != undefined) {
+ console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info('Succeeded in putting data');
+ const mode = distributedKVStore.SyncMode.PULL_ONLY;
+ kvStore.sync(deviceIds, mode, 1000);
+ });
+ } catch (e) {
+ console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
+ }
+
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
```
### sync
@@ -4619,7 +4619,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE**
>
-> **deviceIds** is the **networkId** in [DeviceInfo](js-apis-device-manager.md#deviceinfo), which is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
@@ -4646,43 +4646,44 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example**
```js
-import deviceManager from '@ohos.distributedHardware.deviceManager';
+import deviceManager from '@ohos.distributedDeviceManager';
let devManager;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager
-deviceManager.createDeviceManager('bundleName', (err, value) => {
- if (!err) {
- devManager = value;
- let deviceIds = [];
- if (devManager != null) {
- var devices = devManager.getTrustedDeviceListSync();
- for (var i = 0; i < devices.length; i++) {
- deviceIds[i] = devices[i].networkId;
- }
- }
- try {
- kvStore.on('syncComplete', function (data) {
- console.info('Sync dataChange');
- });
- kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) {
- if (err != undefined) {
- console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
- return;
- }
- console.info('Succeeded in putting data');
- const mode = distributedKVStore.SyncMode.PULL_ONLY;
- const query = new distributedKVStore.Query();
- query.prefixKey("batch_test");
- query.deviceId('localDeviceId');
- kvStore.sync(deviceIds, query, mode, 1000);
- });
- } catch (e) {
- console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
+try {
+ let devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
+ let deviceIds = [];
+ if (devManager != null) {
+ var devices = devManager.getAvailableDeviceListSync();
+ for (var i = 0; i < devices.length; i++) {
+ deviceIds[i] = devices[i].networkId;
}
}
-});
+ try {
+ kvStore.on('syncComplete', function (data) {
+ console.info('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) {
+ if (err != undefined) {
+ console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
+ return;
+ }
+ console.info('Succeeded in putting data');
+ const mode = distributedKVStore.SyncMode.PULL_ONLY;
+ const query = new distributedKVStore.Query();
+ query.prefixKey("batch_test");
+ query.deviceId(devManager.getLocalDeviceNetworkId());
+ kvStore.sync(deviceIds, query, mode, 1000);
+ });
+ } catch (e) {
+ console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
+ }
+
+} catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+}
```
### on('dataChange')
@@ -5046,7 +5047,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean | string |
Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5101,7 +5102,7 @@ get(deviceId: string, key: string): Promise<boolean | string | number | Uint8
Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5281,7 +5282,7 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry
Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5348,7 +5349,7 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]>
Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5544,7 +5545,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5616,7 +5617,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]>
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5824,7 +5825,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVS
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5879,7 +5880,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet&g
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -5935,7 +5936,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -6011,7 +6012,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet>
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -6154,7 +6155,7 @@ getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void
Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
@@ -6343,7 +6344,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System API**: This is a system API.
@@ -6404,7 +6405,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System API**: This is a system API.
@@ -6585,7 +6586,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number&
Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
@@ -6651,7 +6652,7 @@ getResultSize(deviceId: string, query: Query): Promise<number>
Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
-> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
+> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync).
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore