OpenHarmony实战开发:DataAbility组件开发

往期鸿蒙全套实战精彩文章必看内容:


DataAbility组件概述

DataAbility,即"使用Data模板的Ability",主要用于对外部提供统一的数据访问抽象,不提供用户交互界面。DataAbility可由PageAbility、ServiceAbility或其他应用启动,即使用户切换到其他应用,DataAbility仍将在后台继续运行。

使用DataAbility有助于应用管理其自身和其他应用存储数据的访问,并提供与其他应用共享数据的方法。DataAbility既可用于同设备不同应用的数据共享,也支持跨设备不同应用的数据共享。

数据的存放形式多样,可以是数据库,也可以是磁盘上的文件。DataAbility对外提供对数据的增、删、改、查,以及打开文件等接口,这些接口的具体实现由开发者提供。

创建DataAbility

实现DataAbility中Insert、Query、Update、Delete接口的业务内容。保证能够满足数据库存储业务的基本需求。BatchInsert与ExecuteBatch接口已经在系统中实现遍历逻辑,依赖Insert、Query、Update、Delete接口逻辑,来实现数据的批量处理。

创建DataAbility的代码示例如下:

import featureAbility from '@ohos.ability.featureAbility';
import type common from '@ohos.app.ability.common';
import type Want from '@ohos.app.ability.Want';
import type { AsyncCallback, BusinessError } from '@ohos.base';
import dataAbility from '@ohos.data.dataAbility';
import rdb from '@ohos.data.rdb';
import hilog from '@ohos.hilog';

let TABLE_NAME = 'book';
let STORE_CONFIG: rdb.StoreConfig = { name: 'book.db' };
let SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)';
let rdbStore: rdb.RdbStore | undefined = undefined;
const TAG: string = '[Sample_FAModelAbilityDevelop]';
const domain: number = 0xFF00;

class DataAbility {
  onInitialized(want: Want): void {
    hilog.info(domain, TAG, 'DataAbility onInitialized, abilityInfo:' + want.bundleName);
    let context: common.BaseContext = { stageMode: featureAbility.getContext().stageMode };
    rdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
      hilog.info(domain, TAG, 'DataAbility getRdbStore callback');
      store.executeSql(SQL_CREATE_TABLE, []);
      rdbStore = store;
    });
  }

  insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void {
    hilog.info(domain, TAG, 'DataAbility insert start');
    if (rdbStore) {
      rdbStore.insert(TABLE_NAME, valueBucket, callback);
    }
  }

  batchInsert(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void {
    hilog.info(domain, TAG, 'DataAbility batch insert start');
    if (rdbStore) {
      for (let i = 0; i < valueBuckets.length; i++) {
        hilog.info(domain, TAG, 'DataAbility batch insert i=' + i);
        if (i < valueBuckets.length - 1) {
          rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: BusinessError, num: number) => {
            hilog.info(domain, TAG, 'DataAbility batch insert ret=' + num);
          });
        } else {
          rdbStore.insert(TABLE_NAME, valueBuckets[i], callback);
        }
      }
    }
  }

  query(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<rdb.ResultSet>): void {
    hilog.info(domain, TAG, 'DataAbility query start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.query(rdbPredicates, columns, callback);
    }
  }

  update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void {
    hilog.info(domain, TAG, 'DataAbility update start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.update(valueBucket, rdbPredicates, callback);
    }
  }

  delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void {
    hilog.info(domain, TAG, 'DataAbility delete start');
    let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates);
    if (rdbStore) {
      rdbStore.delete(rdbPredicates, callback);
    }
  }
}

export default new DataAbility();

启动DataAbility

启动DataAbility会获取一个工具接口类对象(DataAbilityHelper)。启动DataAbility的示例代码如下:

import featureAbility from '@ohos.ability.featureAbility';
import ability from '@ohos.ability.ability';

let uri: string = 'dataability:///com.samples.famodelabilitydevelop.DataAbility';
let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(uri);

访问DataAbility

访问DataAbility需导入基础依赖包,以及获取与DataAbility子模块通信的URI字符串。

其中,基础依赖包包括:

  • @ohos.ability.featureAbility

  • @ohos.data.dataAbility

  • @ohos.data.relationalStore

访问DataAbility的示例代码如下:

  1. 创建工具接口类对象。

    import featureAbility from '@ohos.ability.featureAbility';
    import ohos_data_ability from '@ohos.data.dataAbility';
    import relationalStore from '@ohos.data.relationalStore';
    import ability from '@ohos.ability.ability';
    // 作为参数传递的URI,与config中定义的URI的区别是多了一个"/",有三个"/"
    let uri: string = 'dataability:///com.samples.famodelabilitydevelop.DataAbility';
    let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(uri);
    
  2. 构建数据库相关的RDB数据。

    import ohos_data_ability from '@ohos.data.dataAbility';
    import rdb from '@ohos.data.rdb';
    let valuesBucket_insert: rdb.ValuesBucket = { name: 'Rose', introduction: 'insert' };
    let valuesBucket_update: rdb.ValuesBucket = { name: 'Rose', introduction: 'update' };
    let crowd = new Array({ name: 'Rose', introduction: 'batchInsert_one' } as rdb.ValuesBucket,
      { name: 'Rose', introduction: 'batchInsert_two' } as rdb.ValuesBucket);
    let columnArray = new Array('id', 'name', 'introduction');
    let predicates = new ohos_data_ability.DataAbilityPredicates();
    

    注:关于DataAbilityPredicates的详细内容。

  3. 调用insert方法向指定的DataAbility子模块插入数据。

    import { BusinessError } from '@ohos.base';
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    this.DAHelper.insert(this.uri, this.valuesBucket_insert, (error: BusinessError, data: number) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'insert_failed_toast'
        });
      } else {
        promptAction.showToast({
       message: 'insert_success_toast'
        });
      }
      Logger.info(TAG, 'DAHelper insert result: ' + data + ', error: ' + JSON.stringify(error));
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import { BusinessError } from '@ohos.base';
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    this.DAHelper.insert(this.uri, this.valuesBucket_insert).then((datainsert) => {
      promptAction.showToast({
        message: 'insert_success_toast'
      });
      Logger.info(TAG, 'DAHelper insert result: ' + datainsert);
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'insert_success_toast'
      });
      Logger.error(TAG, `DAHelper insert failed. Cause: ${error.message}`);
    });
    
  4. 调用delete方法删除DataAbility子模块中指定的数据。

    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    this.DAHelper.delete(this.uri, this.predicates, (error, data) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'delete_failed_toast'
        });
      } else {
        promptAction.showToast({
          message: 'delete_success_toast'
        });
     }
      Logger.info(TAG, 'DAHelper delete result: ' + data + ', error: ' + JSON.stringify(error));
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    this.DAHelper.delete(this.uri, this.predicates).then((datadelete) => {
     promptAction.showToast({
        message: 'delete_success_toast'
      });
      Logger.info(TAG, 'DAHelper delete result: ' + datadelete);
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'delete_failed_toast'
      });
      Logger.error(TAG, `DAHelper delete failed. Cause: ${error.message}`);
    });
    
  5. 调用update方法更新指定DataAbility子模块中的数据。

    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    this.predicates.equalTo('name', 'Rose');
    this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates, (error, data) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'update_failed_toast'
        });
      } else {
        promptAction.showToast({
          message: 'update_success_toast'
        });
     }
      Logger.info(TAG, 'DAHelper update result: ' + data + ', error: ' + JSON.stringify(error));
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    this.predicates.equalTo('name', 'Rose');
    this.DAHelper.update(this.uri, this.valuesBucket_update, this.predicates).then((dataupdate) => {
     promptAction.showToast({
        message: 'update_success_toast'
      });
      Logger.info(TAG, 'DAHelper update result: ' + dataupdate);
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'update_failed_toast'
      });
      Logger.error(TAG, `DAHelper update failed. Cause: ${error.message}`);
    });
    
  6. 调用query方法在指定的DataAbility子模块中查找数据。

    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    this.predicates.equalTo('name', 'Rose');
    this.DAHelper.query(this.uri, this.columnArray, this.predicates, (error, data) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'query_failed_toast'
        });
        Logger.error(TAG, `DAHelper query failed. Cause: ${error.message}`);
      } else {
        promptAction.showToast({
          message: 'query_success_toast'
     });
      }
      // ResultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (data.goToNextRow()) {
     const id = data.getLong(data.getColumnIndex('id'));
        const name = data.getString(data.getColumnIndex('name'));
        const introduction = data.getString(data.getColumnIndex('introduction'));
        Logger.info(TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`);
      }
      // 释放数据集的内存
      data.close();
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    this.predicates.equalTo('name', 'Rose');
    this.DAHelper.query(this.uri, this.columnArray, this.predicates).then((dataquery) => {
      promptAction.showToast({
        message: 'query_success_toast'
      });
      // ResultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (dataquery.goToNextRow()) {
        const id = dataquery.getLong(dataquery.getColumnIndex('id'));
        const name = dataquery.getString(dataquery.getColumnIndex('name'));
        const introduction = dataquery.getString(dataquery.getColumnIndex('introduction'));
        Logger.info(TAG, `DAHelper query result:id = [${id}], name = [${name}], introduction = [${introduction}]`);
      }
      // 释放数据集的内存
      dataquery.close();
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'query_failed_toast'
      });
      Logger.error(TAG, `DAHelper query failed. Cause: ${error.message}`);
    });
    
  7. 调用batchInsert方法向指定的DataAbility子模块批量插入数据。

    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    this.DAHelper.batchInsert(this.uri, this.crowd, (error, data) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'batchInsert_failed_toast'
        });
      } else {
        promptAction.showToast({
          message: 'batchInsert_success_toast'
        });
     }
      Logger.info(TAG, 'DAHelper batchInsert result: ' + data + ', error: ' + JSON.stringify(error));
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    this.DAHelper.batchInsert(this.uri, this.crowd).then((databatchInsert) => {
     promptAction.showToast({
        message: 'batchInsert_success_toast'
      });
      Logger.info(TAG, 'DAHelper batchInsert result: ' + databatchInsert);
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'batchInsert_failed_toast'
      });
      Logger.error(TAG, `DAHelper batchInsert failed. Cause: ${error.message}`);
    });
    
  8. 调用executeBatch方法向指定的DataAbility子模块进行数据的批量处理。

    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // callback方式调用:
    let operations: Array<ability.DataAbilityOperation> = [{
      uri: this.uri,
      type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
      valuesBucket: { name: 'Rose', introduction: 'executeBatch' },
      predicates: this.predicates,
      expectedCount: 0,
      predicatesBackReferences: undefined,
      interrupted: true,
    }];
    this.DAHelper.executeBatch(this.uri, operations, (error, data) => {
      if (error && error.code !== 0) {
        promptAction.showToast({
          message: 'executeBatch_failed_toast'
        });
      } else {
        promptAction.showToast({
          message: 'executeBatch_success_toast'
        });
      }
     Logger.info(TAG, `DAHelper executeBatch, result: ` + JSON.stringify(data) + ', error: ' + JSON.stringify(error));
    }
    );
    
    import featureAbility from '@ohos.ability.featureAbility'
    import promptAction from '@ohos.promptAction';
    import Logger from '../../utils/Logger';
    
    const TAG: string = 'PageDataAbility';
    
    // promise方式调用(await需要在async方法中使用):
    let operations: Array<ability.DataAbilityOperation> = [{
      uri: this.uri,
      type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
      valuesBucket: { name: 'Rose', introduction: 'executeBatch' },
      predicates: this.predicates,
      expectedCount: 0,
      predicatesBackReferences: undefined,
      interrupted: true,
    }];
    this.DAHelper.executeBatch(this.uri, operations).then((dataquery) => {
      promptAction.showToast({
        message: 'executeBatch_success_toast'
      });
      Logger.info(TAG, 'DAHelper executeBatch result: ' + JSON.stringify(dataquery));
    }).catch((error: BusinessError) => {
      promptAction.showToast({
        message: 'executeBatch_failed_toast'
      });
      Logger.error(TAG, `DAHelper executeBatch failed. Cause: ${error.message}`);
    });
    

DataAbility的客户端的接口是由工具接口类对象DataAbilityHelper向外提供


看完三件事❤️

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注作者 ,不定期分享原创知识。
  • 同时可以期待后续文章ing🚀。   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值