Couchbase Tutorial for Android: Getting Started

In this couchbase tutorial, you will learn how to use prebuilt Couchbase Lite databases, model, query, upload and sync data including attachments. By James Nocentini.

Leave a rating/review
Save for later
Share

Couchbase Mobile is a distributed database that runs on mobile devices and on app servers. Having a mobile database under your app results in speedy interactions with your application — even without network connectivity. When connectivity is restored, the full master-master replication automatically synchronizes the data.

Why would you choose Couchbase over the built-in SQLite support or a cloud-based data service?

  • Easy migration: Since Couchbase is built on NoSQL, you can seamlessly change data as your application grows — without requiring elaborate upgrade scripts.
  • Simple data mapping: Couchbase lets you store data in a format that closely resembles how your app uses the data.
  • Built-in synchronization: If you have ever needed to build your own syncing solution, you know how complicated it can be. Couchbase’s Sync Gateway does all of the hard work for you.
  • Offline support: Couchbase lets you develop your app without thinking about a network connection. You simply write to the local database and let Couchbase handle the rest.

In this Couchbase tutorial, you’ll develop a crowd-sourcing quiz application called QuizzDroid. Your answers will be shared (via Sync Gateway) with all other users. So there is no right or wrong answer — only what other users have answered. :]

couchbase tutorial demo

When you’re done, you’ll have learned the following:

  • How to use prebuilt Couchbase Lite databases.
  • How to model and query data including attachments.
  • How to craft data.
  • How to sync data and manage network availability.
  • How to deploy your app to multiple emulators.

Are you excited? Let’s go!

Note: You should have a working knowledge of Android development before working through this Couchbase tutorial. If you need a refresher, take a look at some of our introductory Android tutorials!

Note: You should have a working knowledge of Android development before working through this Couchbase tutorial. If you need a refresher, take a look at some of our introductory Android tutorials!

Getting Started

Download the QuizzDroid starter project and open it in Android Studio. It already contains the Couchbase Lite Android SDK as a dependency and has two activities:

  • HomeActivity will display the list of questions.
  • QuestionActivity will contain the image, possible choices to select from and all answers from other users.

Build and run your app (some configurations of Android Studio may report build errors on the first attempt; in this case, simply build and run again, and you’ll be error-free). As you can see, the screen is empty:

couchbase tutorial image01

You’re now ready to start bringing the activities to life.

Couchbase Mobile is divided into three components:

  • Couchbase Lite: An embedded NoSQL database that runs on the device, within your application.
  • Sync Gateway: An Internet-facing synchronization server that securely syncs data between device and cloud.
  • Couchbase Server: A highly scalable cloud-based NoSQL server used as a storage engine by Sync Gateway.

You’ll use the Couchbase Lite database and the Sync Gateway in this tutorial in a simulated multi-user environment and briefly touch on the Couchbase server component.

Using the Prebuilt Database

Since Couchbase Lite runs right on the device, you can bundle a prebuilt database in your application. This is optional; most apps start with an empty database and add data entered by the user or synchronized through Sync Gateway.

In this Couchbase tutorial, you will use a database containing a list of questions. Download the database and move the zip file to app/src/main/assets/ in the starter project:

couchbase tutorial drag-db-finder

The database starts in the assets folder, but Couchbase Lite reads from and persists to the data/data/com.raywenderlich.quizzdroid/files folder. In the next section you’ll add code to move the database to its final location.

Initializing the Database

Open DataManager.java. This is a singleton class providing access to the database instance throughout the application. Add the following to the constructor:

Manager manager = null;
try {
  // 1
  manager = new Manager(new AndroidContext(context), Manager.DEFAULT_OPTIONS);
  // 2
  database = manager.getExistingDatabase("quizzdroid");
} catch (IOException e) {
  e.printStackTrace();
} catch (CouchbaseLiteException e) {
  e.printStackTrace();
}

// 3
if (database == null) {
  try {
    ZipUtils.unzip(context.getAssets().open("quizzdroid.cblite2.zip"), manager.getContext().getFilesDir());
    // 4
    database = manager.getDatabase("quizzdroid");
  } catch (IOException e) {
    e.printStackTrace();
  } catch (CouchbaseLiteException e) {
    e.printStackTrace();
  }
}

Here’s what this code does:

  1. Instantiates the Couchbase Lite Manager. A Manager is the top-level object managing a collection of Couchbase Lite Database instances. You must create a Manager instance before working with Couchbase Lite objects. The Manager.DEFAULT_OPTIONS parameter indicates default options, including read/write support.
  2. Checks for an existing Database named “quizzdroid”. This line returns null if the database doesn’t exist, as would be the case on first launch.
  3. If the database doesn’t exist, the ZipUtils.unzip method unzips the zip database file into the files directory; otherwise, nothing further needs to be done.
  4. The database is instantiated using the getDatabase method.

Next, instantiate the Manager at the bottom of onCreate in HomeActivity.java:

DataManager manager = DataManager.getSharedInstance(getApplicationContext());

Database Listener

Now that the database is initialized, you should verify it is working properly. This is a perfect job for the Database Listener, which is a component that provides an HTTP entry point to the database. This component is optional and is often used for the following reasons:

  • Debugging: In development, it’s much faster to use the HTTP API to inspect the database than to set breakpoints and examine query results.
  • Peer-to-peer: Other databases (often running on different devices) can persist data to the listener directly without the need for a server to act as the intermediary. This aspect of Couchbase Mobile isn’t covered in this Couchbase tutorial.
  • Hybrid development: Used to access the database from JavaScript frameworks within a WebView.

The image below illustrates the Couchbase system architecture. Notice that a database can communicate directly with another database with a listener, instead of having to use the server as a middle-man.

diagrams.002

Back in DataManager.java, add the following below the existing code in the constructor method:

View.setCompiler(new JavaScriptViewCompiler());
Database.setFilterCompiler(new JavaScriptReplicationFilterCompiler());

Credentials credentials = new Credentials(null, null);
LiteListener liteListener = new LiteListener(manager, 5984, credentials);

Thread thread = new Thread(liteListener);
thread.start();

Be sure to import the Credentials from the com.couchbase.lite.listener namespace.

couchbase tutorial image02

This code creates a database listener on port 5984 and starts it on a background thread.

Build and run your app; you should see the same blank screen as before.

To access the database from a browser or a command-line utility such as curl, you must enable port forwarding for that port using ADB. From the command line, run the following:

adb forward tcp:5984 tcp:5984

Your database is now accessible on http://localhost:5984/quizzdroid.

You can also access the database using the following curl command:

$ curl -X GET 'http://localhost:5984/quizzdroid'

{
  "disk_size":147960,
  "db_uuid":"53b66d23-8803-43f3-a4db-a49d51b09efe",
  "db_name":"quizzdroid",
  "update_seq":6,
  "instance_start_time":1468585759670000,
  "doc_count":6
}

Notice the doc_count is 6, which confirms the prebuilt database was successfully loaded.

Your next task is to display the six questions on the Home Screen.

Contributors

Tom Blankenship

Tech Editor

Chris Belanger

Editor

Odie Edo-Osagie

Final Pass Editor

Matt Luedke

Team Lead

Over 300 content creators. Join our team.