• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# DataShare Development
2The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device.
3
4## Available APIs
5
6**Table 1** APIs of the data provider
7
8|API|Description|
9|:------|:------|
10|onCreate?(want: Want, callback: AsyncCallback<void>): void|Called to initialize service logic when the data provider application is created, for example, when a database is created.|
11|insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Inserts data into the database.|
12|update?(uri: string, predicates: DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Updates data in the database.|
13|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.|
14|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|
15
16For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md).
17
18**Table 2** APIs of the data consumer
19
20| API                                                      | Description                              |
21| :----------------------------------------------------------- | :--------------------------------- |
22| createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance.             |
23| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a single data record into the database.        |
24| update(uri: string, predicates: DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database.          |
25| query(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data from the database.              |
26| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database.|
27
28For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md).
29
30## When to Use
31
32There are two roles in **DataShare**:
33
34- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
35- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
36
37### Data Provider Application Development (for System Applications Only)
38
39[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
40
41- **onCreate**
42
43  Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
44
45- **insert**
46
47  Inserts data. This API is called when the client requests to insert data.
48
49- **update**
50
51  Updates data. This API is called when the client requests to update data.
52
53- **delete**
54
55  Deletes data. This API is called when the client requests to delete data.
56
57- **query**
58
59  Queries data. This API is called when the client requests to query data.
60
61- **batchInsert**
62
63  Batch inserts data. This API is called when the client requests to batch insert data.
64
65- **normalizeUri**
66
67  Converts the URI provided by the client to the URI used by the server.
68
69- **denormalizeUri**
70
71  Converts the URI used by the server to the initial URI passed by the client.
72
73Before implementing a **DataShare** service, you need to create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
74
751. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareAbility**.
76
772. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
78
793. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
80
81   ```ts
82   import Extension from '@ohos.application.DataShareExtensionAbility';
83   import rdb from '@ohos.data.relationalStore';
84   import fileIo from '@ohos.fileio';
85   import dataSharePredicates from '@ohos.data.dataSharePredicates';
86   ```
87
884. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
89
905. 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.
91
92   ```ts
93   const DB_NAME = "DB00.db";
94   const TBL_NAME = "TBL00";
95   const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
96   + TBL_NAME
97   + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
98
99   let rdbStore;
100   let result;
101
102   export default class DataShareExtAbility extends Extension {
103       private rdbStore_;
104
105   	// Override onCreate().
106       onCreate(want, callback) {
107           result = this.context.cacheDir + '/datashare.txt';
108           // Create an RDB store.
109            rdb.getRdbStore(this.context, {
110                name: DB_NAME,
111                securityLevel: rdb.SecurityLevel.S1
112            }, function (err, data) {
113                rdbStore = data;
114                rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
115                    console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
116               });
117               if (callback) {
118                    callback();
119               }
120           });
121       }
122
123   	// Override query().
124       query(uri, predicates, columns, callback) {
125           if (predicates == null || predicates == undefined) {
126               console.info('invalid predicates');
127           }
128           try {
129               rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
130                   if (resultSet != undefined) {
131                       console.info('resultSet.rowCount: ' + resultSet.rowCount);
132                   }
133                   if (callback != undefined) {
134                       callback(err, resultSet);
135                   }
136               });
137           } catch (err) {
138               console.error('error' + err);
139           }
140       }
141       // Override other APIs as required.
142       // ...
143   };
144   ```
145
146
1476. Define **DataShareExtensionAbility** in **module.json5**.
148
149   | Field     | Description                                                  |
150   | --------- | ------------------------------------------------------------ |
151   | "name"    | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
152   | "type"    | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. |
153   | "uri"     | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
154   | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
155
156   **module.json5 example**
157
158   ```json
159      "extensionAbilities": [
160     {
161       "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts",
162       "name": "DataShareExtAbility",
163       "icon": "$media:icon",
164       "description": "$string:description_datashareextability",
165       "type": "dataShare",
166       "uri": "datashare://com.samples.datasharetest.DataShare",
167       "visible": true
168     }
169   ]
170   ```
171
172
173
174### Data Consumer Application Development
175
1761. Import dependencies.
177
178   ```ts
179   import UIAbility from '@ohos.app.ability.UIAbility';
180   import dataShare from '@ohos.data.dataShare';
181   import dataSharePredicates from '@ohos.data.dataSharePredicates';
182   ```
183
1842. Define the URI string for communicating with the data provider.
185
186   ```ts
187   // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
188   let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
189   ```
190
1913. Create a **DataShareHelper** instance.
192
193   ```ts
194   let dsHelper;
195   let abilityContext;
196
197   export default class EntryAbility extends UIAbility {
198   	onWindowStageCreate(windowStage) {
199   		abilityContext = this.context;
200   		dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
201   			dsHelper = data;
202   		});
203   	}
204   }
205   ```
206
2074. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
208
209   ```ts
210   // Construct a piece of data.
211   let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
212   let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
213   let predicates = new dataSharePredicates.DataSharePredicates();
214   let valArray = ['*'];
215   // Insert a piece of data.
216   dsHelper.insert(dseUri, valuesBucket, (err, data) => {
217     console.log("dsHelper insert result: " + data);
218   });
219   // Update data.
220   dsHelper.update(dseUri, predicates, updateBucket, (err, data) => {
221     console.log("dsHelper update result: " + data);
222   });
223   // Query data.
224   dsHelper.query(dseUri, predicates, valArray, (err, data) => {
225     console.log("dsHelper query result: " + data);
226   });
227   // Delete data.
228   dsHelper.delete(dseUri, predicates, (err, data) => {
229     console.log("dsHelper delete result: " + data);
230   });
231   ```
232