Huawei Cloud DB — How to perform CRUD operation
Published: 2022-08-12 07:26:45

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.

`companion object {        
fun initDb() {            AGConnectCloudDB.initialize(ContextProvider.getApplicationContext())        }    
}     
fun dbGetInstance(){  
      mCloudDb = AGConnectCloudDB.getInstance()  
  }`

Then, create a base viewModel to call certain functions of cloud db instead of calling them in every viewModel.
`open class BaseViewModel : ViewModel() {
    var mCloudDbZoneWrapper: CloudDbRepository =
        CloudDbRepository()
    init {
        mCloudDbZoneWrapper.createObjectType()
        mCloudDbZoneWrapper.openCloudDbZone()
    }
}`
Here is what createObjectType() and openCloudDbZone() functions do.
`/*
    Create object type
    */
    fun createObjectType() {
        dbGetInstance()
        try {
            mCloudDb!!.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo())
        } catch (exception: AGConnectCloudDBException) {
            Log.w("CloudDbRepository", exception.errMsg)
        }
    }

    /*
    Following method opens cloud db zone with given configs.
    */
    fun openCloudDbZone() {
        val mConfig: CloudDBZoneConfig = CloudDBZoneConfig(
            "YOUR_CLOUD_DB_NAME", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
            CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC
        )
        mConfig.persistenceEnabled = true

        try {
            mCloudDbZone = mCloudDb!!.openCloudDBZone(mConfig, true)
        } catch (exception: AGConnectCloudDBException) {
            Log.w("CloudDbRepository", exception.errMsg)
        }
    }`

Now we have all settings done. All we need to do is calling executeUpsert() and executeDelete() functions properly in related repositories.
`private fun bookmarkResult(
        snapshot: CloudDBZoneSnapshot<BookmarkStatus>,
        bookmark: BookmarkStatus,
        triggered: Boolean
    ) {
        val bookmarkStatsCursor: CloudDBZoneObjectList<BookmarkStatus> = snapshot.snapshotObjects

        try {
            if (bookmarkStatsCursor.hasNext()) {
                val bookmarkStats = bookmarkStatsCursor.next()
                if (bookmarkStats != null && bookmarkStats.object != null) {
                    if (triggered) {
                        //deleteBookmark
                        val deleteTask = mCloudDBZone.executeDelete(bookmarkStats)
                        deleteTask.addOnSuccessListener {
                            Log.w(TAG, "BookmarkDelete success")
                            bookmarkStatus.postValue(false)
                        }.addOnFailureListener {
                            Log.w(TAG, "BookmarkDelete fail" + it.message)
                        }
                    } else {
                        bookmarkStatus.postValue(true)
                    }
                }
            } else {
                if (triggered) {
                    //add bookmark
                    val upsertTask = mCloudDBZone.executeUpsert(bookmark)
                    upsertTask.addOnSuccessListener {
                        Log.w(TAG, "BookmarkAdd success")
                        bookmarkStatus.postValue(true)
                    }.addOnFailureListener {
                        Log.w(TAG, "BookmarkDelete fail" + it.message)
                    }
                } else {
                    bookmarkStatus.postValue(false)
                }
            }

        } catch (exception: Exception) {
        }
        snapshot.release()
    }`

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39bjduoooorax9zbk970.gif)

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

https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-clouddb-introduction-0000001054212760