How to add or delete record to/from table in Huawei Cloud DB ?

Zehra Yılmaz
Huawei Developers
Published in
3 min readDec 30, 2020

Hello everyone, in this story, I will try to show you basic usage of HMS Cloud Db executeUpsert() and executeDelete() functions.

First, please be sure that having a project on cloud db up and running. If it is your first Cloud Db project and don’t know what to do, feel free to visit here.

For our scenario, we will have two tables named BookmarkStatus and LikeStatus. BookmarkStatus and LikeStatus tables holds a record for each user’s bookmark/like for the specified object and deletes the record when user remove his/her like or bookmark.

Let’s start with initializing our cloud db object. I will initialize cloud db object once when application started (in SplashScreen) and use it through the application.

Note : Make sure you have initialized your cloud db object before any of your cloud db operations.

Then, create a base viewModel to call certain functions of cloud db instead of calling them in every viewModel.

Here is what createObjectType() and openCloudDbZone() functions do.

Now we have all settings done. All we need to do is calling executeUpsert() and executeDelete() functions properly in related repositories.

Note: Please make sure that all needed permissions are granted to add or delete to/from table.

In this function, triggered parameter is for if user clicked bookmark button or not if clicked then value is true.

Here is the logic;

If user bookmarked the given object (which is queried in another method and passed as a parameter to this method as snapshot) then bookmarkStatsCursor.hasNext() returns true and if not triggered , this means user bookmarked the object and is trying to display bookmark status and all we need to do is using postValue() of the observable property bookmarkStatus and pass the value as true. Let’s say user has a record on BookmarkStatus table and triggered is true then we can say user is trying to remove bookmark of the object. So we need to use executeDelete(bookmark) to delete bookmark from table. With the help of addOnSuccessListener we will post value as false which means user does not have a bookmark on the given object anymore.

If user does not have a bookmark in given object and triggered is false, this means user did not bookmark object and trying to display bookmark status. We will post value as false. If triggered is true then, user is trying to add bookmark to that object. In this situation, we will add a record to the bookmark table using executeUpsert(bookmark) method.

Note that you can use addOnFailureListener to catch errors occurred during adding or deleting functions.

To add or delete records to/from LikeStatus table, you can use same logic with BookmarkStatus table given above.

So, as you can see, it is very simple to implement cloud db in your project and you can apply all CRUD functions simply as demonstrated above :)

References

--

--