Couchbase Mobile
Tags: android, database
Published: 2022-02-06 15:15:16

Why Couchbase Mobile?
---

Couchbase Mobile is the complete NoSQL database solution for all data storage, access, sync, and security across the entire
application stack. It includes an Embedded database, Rest API, and Synchronization which is critical for enabling
offline-first mobile apps. The two critical aspects of enabling this are:

- The ability to locally store data on the device so it is always available to the user, whether online or offline
- The ability to sync data to the cloud so it is available to the users on other devices when online. This includes secure routing of data across devices, enforcement of access conflict, and handling of data conflicts.

Couchbase Mobile brings the power of NoSQL to the edge. It is comprised of three important components:

- **Couchbase Lite,** an embedded, NoSQL JSON Document Style database for your mobile apps.

- **Sync Gateway,** an internet-facing synchronization mechanism that securely syncs data between mobile clients and server.

- **Couchbase Server,** a highly scalable, distributed NoSQL database platform.

Installation
---
**1. Couchbase Lite:**

To include Couchbase Lite support within an Android app add the following within _app/build.gradle_

```
dependencies {
    ...

    implementation 'com.couchbase.lite:couchbase-lite-android-ee:2.7.1'
}
```

For more details about how to integrated and use Couchbase Lite follow this [Tutorial](https://docs.couchbase.com/userprofile-couchbase-mobile/standalone/userprofile/android/userprofile_basic.html)


**2. Sync Gateway:**

Click on this [link](https://docs.couchbase.com/sync-gateway/current/gs-sgw-install.html) to download and install Sync Gateway. Follow the instructions carefully and install it based on your Operation System which you use in your machine.

To stop/start the _sync_gateway_ service, use the following:

```
sudo service sync_gateway start

sudo service sync_gateway stop
```

After starting _sync_gateway_ try the following URLs. (URL may differ depending on the PORT NUMBER where it’s installed, but by default these ports are used).

```
http://localhost:4984/

http://localhost:4985/

http://localhost:4985/_admin/
```


**3. Couchbase Server:**

Click on this [link](https://docs.couchbase.com/tutorials/getting-started-ce/install-manage/tutorial_en.html) to download and install Couchbase Server's community version. the server starts automatically after installation. If everything went well during installation and when you open up your browser on
```
http://localhost:8091/
```
you should see the Couchbase Server Web Console then do the following:

- Create a new cluster (Click [here](https://docs.couchbase.com/tutorials/getting-started-ce/install-manage/tutorial_en.html) for more details)
- Create a bucket named `finecract-cn-mobile` and leave the other variables as default.
- Click on the Security tab on the left side and add a user as `Name: fineract-cn, Password: password` and give it _full admin access_ as a role. We use this user to authenticate during replicating data from Mobile to local Couchbase Server.

Data Synchronization
---

In V1.x of Couchbase Mobile, replication was implemented using a REST-based protocol originated by CouchDB over HTTP(s). Effectively, the replication logic was implemented as a series of API calls over HTTP.

To start synchronizing your data with the local server follow the following steps:

**1. Client-Side (Android App)**

- To start replicating data use the following utility class and call the `startReplicating(Database database)` method once you initialize and create Couchbase Database.

```
public class Replicate {

    public static void startReplicating(Database database) throws URISyntaxException {

        Endpoint targetEndpoint = new URLEndpoint(URI.create("ws://10.0.2.2:4984/fineract-cn/"));
        ReplicatorConfiguration config = new ReplicatorConfiguration(database, targetEndpoint);
        config.setReplicatorType(ReplicatorType.PUSH_AND_PULL);
        config.setAuthenticator(new BasicAuthenticator("sync_gateway", "password"));
        Replicator replicator = new Replicator(config);

        replicator.addChangeListener(change -> {
            if (change.getStatus().getError() != null) {
                Log.e(TAG, "Error message:  " + change.getStatus().getProgress());
            }
        });

        replicator.start();
    }
}    
```
in here `targetEndPoint` is the address of the database in Sync Gateway, not the Couchbase server.

- The local server and Android Application should be on the same network.
- Disable the Firewall on the Local Server. (steps might differ depending on the Operating System)
- Create a new file _res > xml > network_security_config.xml_:
```
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>
```
- Make the below changes to the AndroidManifest.xml file:
```
 <application
    ...
    android:networkSecurityConfig="@xml/network_security_config"
    ...>
    
    ...
</application>
```


**2. Configure Sync Gateway**

- Create a file named as `sync-gateway-config.json` with the following configurations:

```
 {
    "log": ["*"],
     "databases": {
        "fineract-cn": {
        "server": "http://localhost:8091/",
        "bucket": "fineract-cn-mobile",
        "username": "fineract-cn",
        "password": "password",
        "enable_shared_bucket_access": true,
        "import_docs": true,
        "num_index_replicas": 0,
        "users": {
            "GUEST": { "disabled": false, "admin_channels": ["*"] },
            "sync_gateway": {"password": "password"}
        }
     }
   }
}
```
- From terminal start the _sync_gateway_ with the created configuration file by running this command:

`/opt/couchbase-sync-gateway/bin/sync_gateway [file_path_address]/sync-gateway-config.json`

- If everyting went well, you can see the `fineract-cn` database name when you open the sync gateway from `http://localhost:4985/_admin/` on the browser.

Sources
---
- The Offline First approach has been implemented in some functionalities of the **Fineract CN mobile** app using Couchbase Lite. Please view this [pull request](https://github.com/jawidMuhammadi/fineract-cn-mobile/pull/2/commits/671e6832c87efc3f7b75f6520cdf077f93951658) to see how it has been implemented. 
- [CouchbaseNote](https://github.com/jawidMuhammadi/CouchbaseNote) is another small project which is created using Couchbase Lite as a Local Data storage.
- [Getting Comfortable with Couchbase Mobile](https://hod.greeley.org/blog/?p=476)
- [Couchbase Mobile](https://www.couchbase.com/products/mobile)
- [Tutorial](https://docs.couchbase.com/userprofile-couchbase-mobile/standalone/userprofile/android/userprofile_basic.html): Getting started with Couchbase Lite and Android.