提交 09f7875e 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 aaff31b5
......@@ -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
......@@ -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<br>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<br>Data can be synchronized between devices in either of the following ways: <br>- Pushing data from a local device to a remote device. <br>- 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
......@@ -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<string>, 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
......@@ -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 = <UDMF.PlainText>(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 = <UDMF.PlainText>(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} `);
}
```
......@@ -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**<br>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)**<br>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)**<br>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 = <UDMF.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 = <UDMF.PlainText>(records[i]);
let plainText = records[i] as unifiedDataChannel.PlainText;
break;
default:
break;
......
......@@ -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|
| -------- | -------- | -------- | -------- | -------- |
| context<sup>10+</sup> | [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<string>, 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<ValuesBucket>, 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);
}
};
```
......@@ -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);
});
```
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册