Over a million developers have joined DZone.

NoSQL on Android

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

There are various NoSQL solutions for mobile platforms such as the iOS and Android. Here, we will look at Couchbase Lite (CBL – the successor of TouchDB), a lightweight, full-featured, embedded JSON database.

Why a full-feature database instead of just a wrapper for a cloud service? Basically, responsiveness. The idea is that the application should always be available to users even when the network is down or slow. Of course, being able to work with data locally also means that we’ll have to sync with the server at some point.

Note that CBL is significantly different from Apache CouchDB despite the “Couch” part.

Now, let’s get down to business and create a small Android application (entire code available onGitHub) which sets up a database using CBL’s Native API, and run basic CRUD operations.

After going through a relatively easy setup ( this one is for good old Eclipse users, that one for Android Studio fans), let’s start by writing some code:

import com.couchbase.lite.*;
import com.couchbase.lite.android.AndroidContext;
/** Database wrapper*/
public class CbDatabase {
private Database database;
private Manager manager;
/** Ctor Setup */
public CbDatabase(String dbname)
throws IOException, CouchbaseLiteException {
// 1. use default settings (read/write access)
manager = new Manager( new AndroidContext(ctx), 
// 2. Check database name given by user
// No upper case allowed in CBL!
// Only the following characters are valid:
// abcdefghijklmnopqrstuvwxyz0123456789_$()+-/
if ( ! Manager.isValidDatabaseName(dbname)) {
// report...
// 3. Get existing db with that name
// or create a new one if it doesn't exist
database = manager.getDatabase(dbname);
//...more methods to come

The code above uses a Manager to set up a database with a valid name. A CBL Database is basically a container for documents. A Manager can create several different databases, each with its own namespace. Here’s how to release all the resources:

/** */
public void close(){
if(manager != null){

Once given the Database object, we are now ready to do CRUD operations on it:

/** C-rud */
public String create( Map<String, Object> docContent )
throws CouchbaseLiteException {
// create an empty document
Document doc = database.createDocument();
// add content to document and save it
return doc.getId();

A CBL Document is the primary entity stored in a database, and has the following attributes:

  • A unique ID (_id property) which can be automatically generated as a UUID
  • A revision ID (_rev property) to keep track of updates
  • A set of key/value pairs forming the body of the Document

Once created, we can retrieve a Document’s content by its id:

/** c-R-ud */
public Map<String, Object> retrieve(String docId){
return database.getDocument(docId)

We can update an existing key/value pair entry in a Document by using a callback:

/** cr-U-d (auto-retry) */
public void update( final String key, final Object value,
String docId )
throws CouchbaseLiteException {
// retrieve the document from the database
Document doc = database.getDocument(docId);
doc.update(new Document.DocumentUpdater() {
/** This may be called more than once */
public boolean update(UnsavedRevision newRevision) {
Map<String, Object> properties = newRevision.getUserProperties();
properties.put(key, value);
return true;

The method retries automatically the update in case of write conflicts by re-reading the Document and re-calling the callback method. That process will continue until the write succeeds. As its name implies, UnsavedRevision is a mutable copy to work with until data is finally persisted to the database.
Deleting a Document is pretty straightforward. Here, we do it by its id:

/** cru-D */
public boolean delete(String docId)
throws CouchbaseLiteException {
// retrieve the document from the database
Document doc = database.getDocument(docId);
// delete the document
return  doc.isDeleted();

Deleting the Document will create a new revision called the “tombstone” (no kidding). It will be marked as deleted so that its status can be replicated to a server when doing a sync. As for updates, this can lead to conflicts if other users made changes to the same Document. In that case, the decision to retry the delete is left to us.

We are now ready to use this wrapper class in our project. First, let’s define our use case: let’s say we need to store locally some user data for our mobile games, like the user email, when the user registered in our system, and a bunch of game scores. Here’s a quick test we can run in our main Activity’s onCreate() method. First, let’s input some data:

// get the current date and time
Date now = new Date();
String nowString = DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(now);
// game scores
List<Double> scores = new ArrayList<Double>();
// create an object that contains data for a document
Map<String, Object> docContent = new HashMap<String, Object>();
docContent.put("email", "Nomad@nomad.com");
docContent.put("registered", nowString);
docContent.put("scores", scores);

Now, the database operations:

CbDatabase db = new CbDatabase("testdb");
// 1. Create
String docId = db.create(docContent);
// 2. Retrieve
Map<String, Object> docContent = db.retrieve(docId);
// 3. Update
db.update("scores", scores, docId);
// 4. Delete
boolean deleted = db.delete(docId);
assert(deleted == true);
catch (Exception e) {
// handle here...
if(db != null){

Here are the corresponding JSON Documents for Retrieve and Update:

// retrieved
scores=[190.0, 210.0, 250.0, 275.0],
registered=June 18, 2014 11:03:18 AM GMT+02:00
// updated scores: note the change in revision 
scores=[190.0, 210.0, 250.0, 275.0, 350.0],
registered=June 18, 2014 11:03:18 AM GMT+02:00

That’s it. Further code details are on GitHub. We just scratched the surface of CBL with this very basic introduction. Unfortunately, the CBL online documentation for Android is incomplete at this time, compared to the one for the iOS. Anyway, there are other important CBL features like adding attachments, Views & Queries, replication (Server & P2P), a REST API, etc. Those would be the subjects of future articles.

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

java ,mobile ,persistence

Published at DZone with permission of Tony Siciliani, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}