[Huawei Developers] Mayism:
Cloud DB is a device-cloud synergy database product that provides data synergy management capabilities between the device and cloud, unified data models, and various data management APIs. In addition to ensuring data availability, reliability, consistency, and security, Cloud DB enables seamless data synchronization between the device and cloud, and supports offline app operations, helping you quickly develop device-cloud and multi-device synergy apps. For more information about Cloud DB, please click here.

Cloud DB can be easily integrated into apps through its SDK and APIs, ensuring security and reliability. During integration, the SDK and APIs ease your workload by performing server setup, deployment, and O&M for you.

Now, let’s first take a look at how to quickly integrate Cloud DB in Android apps. You only need to perform the following three steps:

1. Create an object type and a Cloud DB zone.

2. Export the object type and perform account authentication.

3. Integrate the Cloud DB SDK into your Android project and call APIs to add, delete, modify, or query data.

1. Creating an Object Type and a Cloud DB Zone​

Cloud DB is still in beta, so you’ll need to send an email to apply for the service. For more details on how to do so, please read the following documentation.

1.1. What Is an Object Type?​

Simply put, each object type corresponds to a table used to store data in your database. Think of it as creating an Excel file to store data, whereby each sheet in the Excel file is equivalent to an object type in Cloud DB.

1.2. What Is a Cloud DB Zone?​

A Cloud DB zone is an independent data storage zone. Multiple Cloud DB zones are independent of each other. Going back to the Excel file analogy, imagine that you’re a teacher responsible for multiple classes, and you record the scores of students in each class in an Excel file. Each Excel file contains a student information sheet and a score sheet that are independent of each other. A Cloud DB zone is akin to an Excel file in this analogy.

1.3. Creating an Object Type​

Before you start, apply for and enable Cloud DB by performing the following:

1. Sign in to AppGallery Connect and click My projects. Select your project and app. Go to Build > Cloud DB, click the ObjectTypes tab, and create an object type.

2. Create an object type named StudentInfo. Please remember to set the primary key and select the upsert and delete permissions for the Authenticated user.

1.4. Creating a Cloud DB Zone​

On the Cloud DB Zones tab page, click Add, enter the name of the Cloud DB zone, and click OK.

Before You Start​

When using Cloud DB, you need to export the object type first.

You need to export the object type created in the previous step to your local Android project. This synchronizes data between your Android project and Cloud DB.

Remember to place the exported object type in your Android project. In the example below, I placed the object type in the model directory.

Integrating Cloud DB in Your Android Project​

1. Integrating the Cloud DB SDK​

1. In AppGallery Connect, click My projects, and click a project card. Go to Project settings > General information, and download the agconnect-services.json file in the App information area. Then, place the JSON file under the app directory in your Android project.

2.Configure the project-level build.gradle file.

buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
}
}

allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

3. Configure the app-level build.gradle file.

apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
...
android {
......
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
...
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.300' // Auth Service of AppGallery Connect, for account authentication.
implementation 'com.huawei.agconnect:agconnect-database:1.2.3.301' // Cloud DB SDK.
}

1.1 Preparations

Cloud DB places operation restrictions on users. Only authenticated users can add, delete, and modify data. Therefore, you’ll need to integrate Auth Service first.

Enable Auth Service in AppGallery Connect. Using anonymous account authentication as an example, click My projects, click a project card, and go to Build > Auth Service to enable it.

Sample code for enabling anonymous account authentication:

AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
}
});

2. Completing Initialization​

The initialization consists of three parts: initializing Cloud DB, creating an object type, and creating and opening a Cloud DB zone.

1. Define required parameters in onCreate:

private AGConnectCloudDB mCloudDB;
private CloudDBZoneConfig mConfig;
private CloudDBZone mCloudDBZone;

2.Initialize AGConnectCloudDB.

AGConnectCloudDB.initialize(this);

3.Obtain an AGConnectCloudDB instance and create an object type.

mCloudDB = AGConnectCloudDB.getInstance();
try {
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "createObjectType Failed " + e.getMessage());
}

4. Create and open a Cloud DB zone.

Config = new CloudDBZoneConfig("classs1",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
CloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "openCloudDBZone failed: " + e.getMessage());
}

Note that you can also use the asynchronous openCloudDBZone2 method. The detailed operations are not described here. For details, please refer to:

https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-clouddb-get-started#h1-1594008398022

3. Using Cloud DB Functions​

Once you have completed authentication, you can perform related operations on Cloud DB. The following uses the query operation as an example:

1. In AppGallery Connect, insert two records — test1 and test2 — for testing.

2. Go back to your Android project and call executeQuery to query all data.

Task<CloudDBZoneSnapshot<StudentInfo>> queryTask = mCloudDBZone.executeQuery(
CloudDBZoneQuery.where(StudentInfo.class),
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<StudentInfo>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<StudentInfo> snapshot) {
//
CloudDBZoneObjectList<StudentInfo> InfoCursor = snapshot.getSnapshotObjects();
ArrayList<StudentInfo> infoList = new ArrayList<>();
StudentInfo studentInfo = new StudentInfo();
try {
while (InfoCursor.hasNext()) {
studentInfo = InfoCursor.next();
infoList.add(studentInfo);
}
Log.i("CloudDB", "query success: " + JSONArray.toJSONString(studentInfo));
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "query failed: " + e.getMessage());
}
snapshot.release();
}
});

3. Then, you can view the corresponding query data in Logcat.

4. You can refer to the configuration guide and API reference to learn more about the add, delete, and modify operations:

Configuration guide:

https://developer.huawei.com/consum...allery-connect-Guides/agc-clouddb-insert-data

API reference:

https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb

Summary​

You can use Cloud DB after performing just three easy steps:

1. Create an object type and a Cloud DB zone.

2. Export the object type to an Android project.

3. Integrate the SDK into the Android project and call related APIs.

Once you have completed these steps, you will have integrated a database system into your app, without having to perform any setup or deployment operations. Currently, Cloud DB is still free to use.

Cloud DB links:

Development guide:

https://developer.huawei.com/consum...llery-connect-Guides/agc-clouddb-introduction

API reference:

https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb

Demo:

https://github.com/AppGalleryConnect/agc-demos/tree/main/Android/clouddb-java