Powering Hybrid Mobile Apps with Couchbase

DZone 's Guide to

Powering Hybrid Mobile Apps with Couchbase

· Java Zone ·
Free Resource

Written by Sam Basu for Telerik Mobile Blog.


Every mobile app represents an opportunity for your ideas and creativity to reap rich dividends. You have put in the due diligence to decide on your data storage mechanism – whether to go with SQL or NoSQL. Given the nature of your non-relational data and potential scale of operations, you choose to go with NoSQL. And your chosen provider is Couchbase. Wise choice my friend.

Also, after much consideration, you decide to reuse your web skills to make a hybrid cross-platform mobile app. After all, who wouldn’t want to have their app run on every mobile platform while maintaining a single codebase? And you have chosen to use Telerik AppBuilder for end-to-end mobile tooling and all the required build/deployment services. So far, your choices have been spot on. In this article, we’ll walk through how easy it is to get started integrating and managing your NoSQL storage through Couchbase Mobile inside your hybrid mobile app project, for a consistent user experience.

Couchbase Mobile

In case you do not already know what Couchbase Mobile is and how can it help your mobile app, let me quote:

Couchbase Mobile enables mobile app developers to easily create a new breed of apps that are always-available, fast and responsive even when the network has gone underground. By using Couchbase Mobile developers can quickly create content-rich offline-ready apps that drive user engagement and productivity.

Basically, it takes care of much of developer plumbing and allows you to focus on building your amazing app. There are three components to it:

  1. Couchbase Lite – A standalone on-device lightweight embedded JSON database; you will use this to stow away data locally on the mobile device with full CRUD (Create | Read | Update | Delete) features.
  2. Sync Gateway – The bridge that allows you to securely synchronize on-device Couchbase Lite data with Couchbase Server backend.
  3. Couchbase Server – A high performance scalable JSON database that serves as your backend in the cloud.

Couchbase Lite Plugin

The Couchbase Lite Verified plugin for hybrid mobile apps offers you easy integration with a powerful on-device native NoSQL JSON database, as well easy setup for sync functionality with backend services. You can use the plugin with any Cordova-based hybrid mobile app, but, if using Telerik AppBuilder, we make the integration drop dead easy. Simply head to the Couchbase Lite Plugin website, as shown below, and hit the big Try Plugin in AppBuilder button.


Wait for the unicorns to finish their magic and you’ll be taken to the Telerik Platform dashboard, where all you have to do is sign in. If you do not yet have an existing subscription to the Telerik Platform, simply sign up for a free trial. To showcase the power and ease of using the Couchbase Lite plugin in your hybrid mobile apps, you’ll find that a sample project (as seen below) has been created in a default Workspace (which is essentially a placeholder for projects).


Look inside the Project Navigator window in your project and you’ll see that all of the required files for Couchbase Lite plugin to work in your app have already been added, as shown below.


Also, open the Properties file and you’ll notice that in the Plugins tab, the Couchbase Lite plugin has been already enabled for your app, as seen below.


These configuration pieces are automatically added to make your integration with Couchbase Lite as seamless as possible. The sample AppBuilder project is for a ‘ToDoLite’ hybrid app and it is ready to be run – simply fire up the AppBuilder simulators or deploy the app easily to your mobile device. You have a fully-functional ToDo list app powered by Couchbase Lite – it’s that easy.

If you’re not into using the AppBuilder In-Browser client, simply head back to the Couchbase Lite plugin page and download the bits. You can then use the available instructions to integrate the plugin into your AppBuilder hybrid app project using any IDE of your choice – CLI, Visual Studio extension or the standalone Windows AppBuilder client. Inside the AppBuilder In-Browser client for a pre-existing project, you can always pull in the Couchbase Lite plugin from the Plugins Marketplace – there is an integrated user interface through package manager when you right click on your project, as shown below.


Get Started with Code

If walking through a pre-built sample app is not your thing, let’s write some code from scratch. Assuming that you have the Couchbase Lite plugin already included in your AppBuilder hybrid app project, getting started is actually quite easy. Let’s build the basic workings of a ToDo list app which will have a NoSQL document database on device from which we are going to read/write/query data.

Couchbase Lite works with the same semantics as the Couchbase Server and based on a RESTful API on top of the document database,that lets apps talk with device storage in a wide variety of ways. The Couchbase Lite plugin is initialized through cblite and when ready, we need to get the URL of the Couchbase JSON database instance created inside our device. Here’s the code:

var app, db;

document.addEventListener('deviceready', function () {

         app = new kendo.mobile.Application(document.body, {
               skin: 'flat',
               initial: 'views/home.html'
}, false);

function couchbaseSetup(){
         cblite.getURL(function(err, url) {
         if (err){
                alert("CouchbaseLite Initilization error "+ JSON.stringify(err))

         // All good.
         alert("Couchbase Embedded DB URL: " + url);
         db = coax([url, "todos"]);

Let’s understand what’s going on in the code. First up, we need to wait for the deviceready event – this is our indication that the Cordova framework is ready to do it’s magic. Next, I’m using Kendo UI Mobile to initialize my app. You can, of course, use any other available template or roll your own here. Next up, we fire up the all important cblite.getURL() method, which essentially asks for the URL of the Couchbase JSON database on the device so that we can interact with it. Since this is just for demo purposes, let me just throw up a messagebox with the URL we get back, as seen below.


Now, notice this line of code in the previous code block?

db = coax([url, "todos"]);

Essentially, once we have the URL of the Couchbase document database, we can run CRUD against it over a REST API. But why hand-code all of that when there is a nice wrapper? Coax is an open source client that makes CRUD operations a breeze against any Couchbase database. We simply initialize Coax by handing it our Couchbase URL and pointing towards a todos database collection. If you are interested, take a look at the module.js file in the AppBuilder Couchbase Lite sample project to see how Coax is being hooked up.

Data Management

Now that we’re using Coax and have a handle on the Couchbase Lite on-device document repository, the rest of the data manipulation should be very simple. First, let’s create our named database – we will try to find the database, and on error, create a new database if necessary. This is achieved through simple db.get() and db.put() functions. Here’s the code:

// Try getting DB.
db.get(function(dbgeterror, getresponse){
      if (dbgeterror){
              // Create DB if needed.
              db.put(function(dbcreateerror, putresponse){
                 if (dbcreateerror){
                        alert("DB created");

      // See what DB Get brings back.

Just for demo purposes, I throw up the db.get() response once we have created our named (todos) document database, as shown below.


Now that our named document database has been set up, CRUD operations on the data are incredibly easy. We can read/write pure JSON – no object relational mapping is needed. Since we’re building a ToDo list application, let’s create a ToDo item, write it to disk, read it back out and then delete the record. All this is achieved using simple functions like db.post(), db.get() and db.delete(), with the ID of the record being unique. Here’s the sample code:

// Sample Insert.
var sampletodo = {
                 "_id": "ToDo Item",
                 "text": "Do groceries",
                 "completed": false

db.post(sampletodo, function(inserterror, ok){
        // Read what was just inserted.
        db.get("ToDo Item", function(fetcherror, fetchresponse){

        // Drop the record.
        db.delete("ToDo Item", function(deleteerror, deleteresponse){});

Here’s an alert message showing the response from reading the record – exactly what we inserted into the database, as shown below. With full CRUD operations supported with ease, you can now envision the rest of the ToDo list app coming together.


Data Sync

So far, we’ve seen that the Couchbase Lite plugin allows for non-relational data storage as a JSON database and easy data manipulation on a mobile device. But this is only half the story, as any mobile developer would tell you. What good is data if it is only local on a device? You want the continued user experience of using the data from anywhere or from any device. Data needs to roam so it can follow the user and maintain consistency from any mobile client. This necessitates storing the data centrally somewhere outside of the device, arguably done with most flexibility on the cloud.

We want the local device data to stay in sync with backend server data at all times. But mobile devices roam frequently in areas with no connectivity – as developers, we want to do as little work as possible to make the data sync smart to be able to handle connectivity issues. Enter Couchbase Sync Gateway.

Couchbase Sync Gateway is an easy-to-use scalable smart sync solution. It is a sync server that handles user authentication/authorization, access control, data routing, update validation, and multi-master replication between Couchbase Server and mobile client devices. Setting up the sync gateway is rather easy.

Remember the sample ToDoList AppBuilder project that was created to try out Couchbase Lite plugin? It already knows how to talk to a Couchbase Sync Gateway, to sync local data with a Couchbase server repository. Look at the index.js file for detailed implementation. The sample app connects to a demo Couchbase server instance and a sync gateway is already configured. You can download and run the cross-platform sync gateway locally as a service or use a hosted one from the cloud. The documentation includes further steps on configuring the sync gateway.

Alternatively, if you’re using the sample ToDoList app project, simply update the REMOTE_SYNC_URL variable in the index.js file within the demo project to point to your server or hosting service where a sync gateway is running. Voila! Couchbase Sync Gateway smartly now syncs JSON document data between mobile device and backend server. You can connect multiple devices running the client app to the same server through the sync gateway, and see data changes in real time between clients/server. Good times!

On a similar note, you could also consider using Telerik Backend Services to empower your hybrid mobile apps with easy data storage. Backend Services stores all your relational or non-relational data, and provides easy SDKs/APIs for consumption in any programming language. It integrates with Kendo UI DataSource for simple CRUD operations and you could also easily add offline support to your mobile app. Choice is a good thing for developers!


Hybrid cross-platform mobile apps provide app developers with the luxury of maintaining a single codebase, while having the app work across any mobile platform. Telerik AppBuilder is the perfect companion to build your hybrid app with flexibility of IDE to use and easy build/deployment services. The Couchbase Lite plugin allows hybrid mobile apps to use an on-device JSON document database over a simple REST API. The Couchbase Sync Gateway provides the perfect use case of keeping local data in sync with backend Couchbase server. You have Couchbase wrappers for effective handling of NoSQL data on mobile devices with full CRUD operations and with a backend server being kept in sync seamlessly. That’s a wrap using Couchbase Lite inside Telerik AppBuilder to power your hybrid mobile apps. Head over to the Telerik Plugins Marketplace and get started with your needed plugins today. Go ahead and build your next amazing app idea – the technology is here!

Header image courtesy of Naama ym


Published at DZone with permission of Burke Holland , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}