[Huawei Developers] ask011:
Introduction

In this article, we will be learning how to integrate the Huawei Site kit and Cloud DB integrations in Android using Kotlin. Using AGC Cloud DB service, Service Providers from multiple cities can manage their data through CRUD (Create, Read, Update and Delete) operations. Using Site Kit user can search nearby stores and check stores details.

Development Overview

You need to install Android Studio and I assume that you have prior knowledge about the Android and Kotlin

Hardware Requirements

A computer (desktop or laptop) running Windows 10.

A Huawei phone (with the USB cable), which is used for debugging.

Software Requirements

Java JDK 1.7 or later

Android studio installed.

HMS Core (APK) 4.x or later

Integration of Site Kit

Site Kit provides place search services including keyword search, nearby place search, place detail search, and place search suggestion, helping your app provide convenient place-related services to attract more users and improve user loyalty.

Step 1: To integrate Site kit, need to add the below library:

implementation 'com.huawei.hms:site:5.0.2.300’

Step 2: How to get API Key?

Create an app in AppGallery Connect enter all necessary information.

Generate and configure the signing certificate fingerprint.

Add the AppGallery Connect plug-in and the Maven repository in the project-level build.gradle file. Configure the signature file in Android Studio.

For details, refer to Preparations for Integrating HUAWEI HMS Core.

After configure project, you can find API key in below image.

Step 3: To initialize HMS Site kit:

searchService = SearchServiceFactory.create(this, Utils.getApiKey())

To fetch nearby stores based on user’s current location:

SearchServiceActivity.kt

intent.let {
val request = NearbySearchRequest().apply {
queryString=it.getStringExtra(AppConstants.REQUEST_QUERY).toString()
setQuery(queryString)
setLocation(
Coordinate(
it.getDoubleExtra(AppConstants.SERVICE_LAT_KEY, 0.0),
it.getDoubleExtra(AppConstants.SERVICE_LNG_KEY, 0.0)
)
)
}
imageString = it.getStringExtra(AppConstants.PROVIDER_IMAGE_KEY).toString()
searchService?.nearbySearch(request, searchResultListener)
}

Results

Note: For more details, refer Site kit integration procedure. Site kit- SDK integration

Integration of Cloud DB

In this scenario, we can learn about a database service that runs on a cloud and is accessible from anywhere. Find the following points for better understand:

How to use Cloud DB to develop applications?

How to read, write and query application data to Cloud DB?

This service provides the synergy database product that provides data synergy management capabilities between the device and the cloud, unified data models, and various data management APIs.

Cloud DB supplies us simply cloud database and our project work together successfully and we can take advantages of CRUD (Create, Read, Update and Delete) operations.

Prerequisites

To use the Cloud DB for build application service, you need to complete the following preparations:

You have registered an account on the AppGallery Connect console and passed real-name authentication.

You have created a project and application on the AppGallery Connect console.

You have enabled the Anonymous account authentication service for the application to use permissions of the authentication user.

You have installed Android Studio on the local host.

Enable Cloud DB Service

Before using the Cloud DB service, you need to enable it.

Log in to AppGallery Connect and click My Projects.

Select a project from the project list and click an app for which you need to enable the Cloud DB service.

In the navigation bar, choose Build > Cloud DB.

Click Enable now to enable the Cloud DB service.

Select the Data storage location.

After the service is initialized, the Cloud DB service is enabled successfully.

Adding and Exporting Object Types

The following example shows how to create object types on the AppGallery Connect console and export the object type file in the Java format for Android application development.

1. Log in to AppGallery Connect and click My projects.

2. Select a project from the project list and click an app for which you need to add an object type.

3. In the navigation bar, choose Build > Cloud DB.

4. Click Add to navigate to the object type creation page.

5. Set Object Type Name to LoginInfo, and click Next.

6. Click “+Add Field”, add the fields as per your requirements and click Next.

7. (Optional) Click “+Add Index”.

8. Add permissions as follows and click Next. (For Everyone, upsert and delete access is not allowed).

9. Click OK. Object types are created and displayed in the object type list.

The created object types are displayed in the object type list.

Repeat the above steps to create to create multiple table.

10. Click “Export” button

11. Set the format of the file to be exported to JAVA.

12. Set the Java file type to Android.

13. Enter the package name in the JAVA file.

The package name can contain only the following three types:\

Letters: A–Z or a–z, which are mandatory

Digits: 0–9

Special characters: underscore (_) and period (.)

15. Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project. The file that contains all object types in the version is exported to the local PC. The exported Java file will be added to the local development environment in subsequent steps.

Cloud DB Zone

You can create a Cloud DB zone on the AppGallery Connect console. Perform the following steps to set Cloud DB Zone Name.

1. Log in to AppGallery Connect and click My projects.

2. Select a project from the project list and click an app for which you need to add a Cloud DB zone.

3. In the navigation tree, choose Build > Cloud DB.

4. Click the Cloud DB Zones tab.

5. Click Add to go to the Cloud DB zone creation page.

6. Enter Your App Name in the Cloud DB Zone Name text box.

7. Click OK the created Cloud DB zones are displayed in the Cloud DB zone list.

Configuring the Development Environment

Add a Cloud DB SDK to the dependencies node in the build.gradle file in the Project/app directory.

implementation <strong>'com.huawei.agconnect:agconnect=database:1.2.3.301’</strong>

In the build.gradle file, set the compatibility mode of Java source code to JDK1.8.

compileOptions {

sourceCompatibility = 1.8

targetCompatibility = 1.8

}

Adding Object Type Files

During application development, you can directly add the JAVA files exported from the AppGallery Connect console to the local development environment, and use the createObjectType() method in the AGConnectCloudDB class to define and create object types. Then you do not need to create object types for local application development.

Add all exported files to the local development environment.

Initialize Cloud DB. Use the createObjectType() method in the AGConnectCloudDB class to define and create object types.

Initializing

After adding an object type file, you can use the Cloud DB to develop an application. When developing an application, you need to initialize AGConnectCloudDB, and create Cloud DB zone and object types.

Initialize AGConnectCloudDB in an application’s CloudDBZoneWrapper

public static void initAGConnectCloudDB(Context context) {

AGConnectCloudDB.initialize(context);

}

Obtain the AGConnectCloudDB instance and create object types.

mCloudDB = AGConnectCloudDB.getInstance();
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());

Create the Cloud DB zone configuration object and open the Cloud DB zone. Add the below code in CloudDBZoneWrapper class.

public void openCloudDBZoneV2() {
mConfig = new CloudDBZoneConfig(AppConstants.URBAN_HOME_SERVICES,
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
Log.w(TAG, "open clouddbzone success");
mCloudDBZone = cloudDBZone;
// Add subscription after opening cloudDBZone success
mUiCallBack.onInitCloud();
addSubscription();
}).addOnFailureListener(e ->
Log.w(TAG, "open clouddbzone failed for”));
}

Writing Data

You can use the executeUpsert() API to write one object or a group of objects to the current Cloud DB zone.

Add the below code in CloudDBZoneWrapper class.

public void insertDbZoneInfo(T objectInfo) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> upsertTask = mCloudDBZone.executeUpsert(objectInfo);
upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
mUiCallBack.onInsertSuccess(cloudDBZoneResult);
}).addOnFailureListener(e -> {
mUiCallBack.updateUiOnError("Insert table info failed");
});
}

Viewing Data

Data added on the application page will be stored on the cloud. After a listener for data changes is registered on the device, the device will be notified when there is any changes on the cloud, and the local data will be updated in time.

You can use the query condition together with the subscribeSnapshot() method to specify an object to be listened on. When the data of the object is changed, the device will be notified and the original data stored on the cloud will be synchronized to the device based on the data changes information obtained by snapshots.

Add the below code in CloudDBZoneWrapper class.

private OnSnapshotListener<T> mSnapshotListener = (cloudDBZoneSnapshot, e) -> {
if (e != null) {
Log.w(TAG, "onSnapshot" );
return;
}
CloudDBZoneObjectList<T> snapshotObjects = cloudDBZoneSnapshot.getSnapshotObjects();
List<T> dbZoneList = new ArrayList<>();
try {
if (snapshotObjects != null) {
while (snapshotObjects.hasNext()) {
T objectInfo = snapshotObjects.next();
dbZoneList.add(objectInfo);
}
}
mUiCallBack.onSubscribe(dbZoneList);
} catch (AGConnectCloudDBException snapshotException) {
Log.w(TAG, "onSnapshot:(getObject)");
} finally {
cloudDBZoneSnapshot.release();
}
};

Querying Data

The executeQuery(), addOnSuccessListener(), and addOnFailureListener() methods are used together to query data in asynchronous mode.

Add the below code in CloudDBZoneWrapper class.

public void queryAllData(CloudDBZoneQuery<T> query) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<CloudDBZoneSnapshot<T>> queryTask = mCloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<T>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<T> snapshot) {
processQueryResult(snapshot);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
mUiCallBack.updateUiOnError("Query failed");
}
});
}

Deleting Data

You can use the executeDelete() method to delete a single object or a group of objects. When deleting data, Cloud DB will delete the corresponding data based on the input object primary key and does not check whether other attributes of the object are consistent with the stored data. When a group of objects are deleted, the deletion operation is atomic. That is, objects in the list are either all deleted successfully or all fail to be deleted.

Add the below code in CloudDBZoneWrapper class.

public void deleteTableData(List<T> tableObject) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> deleteTask = mCloudDBZone.executeDelete(tableObject);
if (deleteTask.getException() != null) {
mUiCallBack.updateUiOnError("Delete service type table failed");
return;
}
mUiCallBack.onDelete(tableObject);
}
}

Editing Data

You can use the editService() method to edit professional’s details.

Add the below code in ManageServiceActivity.kt class.

override fun editService(listObject: ServiceType) {
val intent = Intent(this, AddServiceActivity::class.java)
intent.apply {
putExtra(AppConstants.CATEGORY_NAME, listObject.cat_name)
putExtra(AppConstants.PROVIDER_PH_NUM, listObject.phone_number.toString())
putExtra(AppConstants.PROVIDER_MAIL_ID, listObject.email_id)
putExtra(AppConstants.PROVIDER_COUNTRY, listObject.country)
putExtra(AppConstants.PROVIDER_ID, listObject.id)
putExtra(AppConstants.PROVIDER_NAME, listObject.service_provider_name)
putExtra(AppConstants.PROVIDER_CITY, listObject.city)
putExtra(AppConstants.PROVIDER_STATE, listObject.state)
}
startActivity(intent)
}

Results

Tips and Tricks

Always use the latest version of the library.

Always provide proper Roles to user in Object Types.

Note: For more details, please refer Cloud Db service integration documentation, Cloud DB- Introduction

Conclusion

By using Cloud DB you can connect with Database without the need of APIs. You can perform the CRUD operations and also can restrict user access for the tables. Easy to connect with the application. Also you can search nearby service (plumber, electrician, painter etc) using site kit like as etc.

Site Kit to fetch nearby stores.

Cloud DB service to add, delete and edit professional’s details.

References

Site Kit

Cloud DB- Applying for Cloud BD

Cloud DB- Introduction

Read In Forum