Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Offline-First Android Applications With NoSQL: Part 2

DZone's Guide to

Offline-First Android Applications With NoSQL: Part 2

The second part of Nic Raboy's article about making your Android applications offline-first.

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

If you're just joining us, you can read part one here

Solutions to an Offline-First Experience

To be successful with offline-first development, the applications you develop will need to have a local database. Like I mentioned earlier, this will allow your function to access data even without an internet connection.

The question now becomes how do you keep the local database in sync with the remote database when a connection is available? Many have tried to solve this, but the NoSQL database company, Couchbase, has managed to do this particularly well.

Couchbase Mobile 

Couchbase has a lineup of platforms that compose what it calls Couchbase Mobile. Composed of Couchbase Lite and Couchbase Sync Gateway, developers can use Couchbase Mobile to make truly offline-first mobile applications using minimal code and NoSQL.

What are these Couchbase components and how do they fit together?

Couchbase Lite

Couchbase Lite is an embedded NoSQL databases that ships with your Android or iOS mobile application. Previously shown in the comparison between SQLite and NoSQL, Couchbase Lite lets you use NoSQL within your app without being constrained to tables, rows, and columns of a relational database.

Couchbase Sync Gateway

Couchbase Lite is only a local database. It is always available, but how does one synchronize that data to and from a remote database server?

Couchbase Sync Gateway is an application server that acts as your data router between the local Couchbase Lite database and Couchbase Server. Changes are recognized in both
the local instance and remote instance and updated where appropriate. It handles partitioning data, user authorization and authentication, and collision management. Many devices may be changing the same data when others are not online. When this happens, devices may step on each other. The collision management of Couchbase Sync Gateway handles this to prevent the chaos typically found when designing a synchronization system.

Couchbase Server

Couchbase Server is a very performant, highly scalable, open source NoSQL document database. It acts as your remote database that can be accessed not only by web applications created in languages such as Node.js or Java, but also Couchbase Mobile.

Offline-First Through Example

At this point you should have a good sense of offline-first practices and tools that will help when developing Android applications.

Let’s run through some examples demonstrating that it isn't a stretch to get offline-first working within all Android applications. It should be noted that the following examples use Couchbase Mobile.

Saving Local Data to the Android Device

A fragment of what it takes to save data into the Couchbase Lite database was shown earlier. Let’s make it more complete:

public void insert(String firstname, String lastname) { 
  Map<String, Object> docContent = new HashMap<String,
Object>();
docContent.put(“firstname”, firstname); 
  docContent.put(“lastname”, lastname); 
  Document document = couchbaseDatabase.
createDocument(); 
  try {
document.putProperties(docContent); 
    } catch (CouchbaseLiteException e) {
Log.e(TAG, “Cannot write document to database”, e);
} 
}

The only thing different in the above insert snippet is, that first we’ve started the database manager and opened a particular database.

Just like that, documents are created in the database.

Syncing Data Between the Device and Database Server

There are two components when it comes to synchronization with Couchbase Lite and Couchbase Sync Gateway. The sync must be started via the Android application code, and the con guration that consists of data partitioning, authentication, etc., must be established in the Couchbase Sync Gateway application server.

To start synchronizing in both directions from the mobile device, the following would be added:

Manager couchbaseManager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS); Database couchbaseDatabase = couchbaseManager. getDatabase(“my-db-name-here”);
Replication pull = couchbaseDatabase. createPullReplication(new URL(“http://192.168.57.1:4984/ todos”));
Replication push = couchbaseDatabase. createPushReplication(new URL(“http://192.168.57.1:4984/ todos”));
pull.setContinuous(true);
push.setContinuous(true);
pull.start();
push.start();

The above snippet would sync data in both directions to a remote Couchbase Sync Gateway server found at 192.168.57.1:4984 with database todos.

The Couchbase Sync Gateway Configuration

Finally, in its most basic state, a Sync Gateway con guration might look like the following:

{
“log”:[“CRUD+”, “REST+”, “Changes+”, “Attach+”], “databases”: {
“todos”: { 
“server”:”walrus:data”, 
“sync”:`
function (doc) {
channel (doc.channels); 
            }
`, 
        “users”: {
“GUEST”: {
“disabled”: false,
“admin_channels”: [“*”] 
            }
        } 
        }
    } 
}

Of course there is no partitioning logic and authentication logic above, but there certainly could be. 

Viewing the Data in Your Database

With data synchronizing back and forth when an internet connection is available, you’re going to want your Android UI to be able to reflect these changes or read the data. This can be done via simple queries or change listeners.

Say for example you only want to query your database in a similar fashion to what you would with SQLite. You would first create a Couchbase Lite View which is similar to a query, then execute it A Couchbase Lite View is how documents get indexed in your Couchbase Lite database. An example being something like so:

Manager couchbaseManager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS); 
Database couchbaseDatabase = couchbaseManager. getDatabase(“my-db-name-here”);

View myView = couchbaseDatabase.getView(“findTwitter”); 
myView.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
List<String> twitters = (List) document. get(“twitter”);
for (String twitter : twitters) { 
        emitter.emit(twitter, document.get(“firstname”));
} 
}
}, “2”);

Query query = couchbaseDatabase.getView(“findTwitter”). createQuery();

In the above, a view is established for finding Twitter and naming information. It only needs to be established once within an app. Then the view can be queried throughout the application as often as you’d like.

Conclusion

There are many different “first” approaches, but to leave your Android application with the performance it deserves under all circumstances, **offline-first** is the way to go. By switching from SQLite to NoSQL in Android, you are left with the freedom to do whatever you want, whenever you want with your data, making synchronization solutions like Couchbase Mobile and Couchbase Server ideal.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:
mobile ,nosql ,sqlite

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}