Webinar - Developing with Couchbase lite on Android

Preview:

DESCRIPTION

Learn how to develop with Couchbase Lite for Android in this technical lecture led by Traun Leyden, lead Couchbase Lite Android developer. The session will include a look into the Java native APIs, using a walkthrough of a demo app. Other topics include: A 5-minute recap of the Couchbase Lite architecture A step-by-step demonstration on how to develop an Android application with Couchbase Lite An explanation of the future plans for Couchbase Lite Android

Citation preview

Developing WithCouchbase Lite on Android

Traun Leydentleyden@couchbase.com

10/29/13

Webinar Overview

• Understand the overall problem

• Overview of the Couchbase Mobile solution

• Couchbase Lite for Android­ Demo­ Code and Concepts walkthrough

• Where to go from here

Bird’s eye view of the Problem

• Syncing data to the Cloud and other devices • Writing your own sync engine is hard

• Poor network conditions / offline

• Sometimes data doesn’t fit into a nice relational model

• Schema migrations can be challenging• Multiple versions of devices in the field

For more information

• See Couchbase Mobile Overview Webinar ­ http://info.couchbase.com/couchbase-mobile-webinar-overview-on-de

mand-May.html

Couchbase Lite on Android

• Installation and setup walk-through

• Demo of Grocery Sync sample app

• Tour of Grocery Sync code

Installation setup and walk-through

• Clone the GrocerySync-Android repository

• Import into Android Studio

• Build & Run

1. Clone the GrocerySync-Android repository

$ git clone git@github.com:couchbaselabs/GrocerySync-Android.git

Quick note on how GrocerySync includes Couchbase Lite

repositories {

mavenCentral()

maven {

url "http://files.couchbase.com/maven2/"

}

mavenLocal()

}

dependencies {

compile 'com.android.support:support-v4:13.0.+'

compile 'com.couchbase.lite:couchbase-lite-android:1.0.0'

}

Alternatively, with a few tweaks in can depend directly on the source.

Import into Android Studio 0.5.7or later

Choose Import Project ..

Import into Android StudioChoose the folder

you did the git clone into

Build and Run

Hit the Run button to launch

the app

Build and Run

The emulator will launch runningGrocery Sync

Live Demo

Demo Recap• We were able to create, update, and delete records

• Verified that documents were Sync’d between devices

• Demo conflict resolution

A Tour of the Codeand the API

Initialization

// Initialize Couchbase Lite protected void startCBLite() throws CouchbaseLiteException { context = new new AndroidContext(this); manager = new Manager(context, Manager.DEFAULT_OPTIONS); database = manager.getDatabase(DATABASE_NAME); .. }

1

2

3

Manager

Database“otherdb”

Database“db”

Document “doc3”

Document“doc2”

Document“doc1”

Document “doc1”{­­“text”:­“Shaving­Cream”,­­“created”:­“2013-10-08”,­­“check”:­­­false}

thumb.jpg

Manager, Databases, Documents

Manager

• Collection of named databases

• Typically you will use a single manager

• Manages database storage (local directory)

Database

• Not a wrapper for a cloud service

• Namespace for documents

• Contains views and their indexes

• Contains validation functions

• Source and target of replication

Document

• Has unique ID within its database

• Contains arbitrary* JSON object­ *except keys that start with “_” are reserved­ There is no explicit, enforced schema­ Denormalization is OK — use arrays or dictionaries

• May contain binary attachments­ Data blobs, can be large, tagged with MIME type

• Versioned­ Multi-Version Concurrency Control (MVCC)­ Every update creates a revision ID (based on digest of contents)­ Revision ID history is stored­ Enables conflict resolution in syncing­ Very painful if you try to build this yourself

View“completed”

Views & Queries

Database“db”

View“byDate”

Query}

function(doc)­{­­emit(doc.created_at,­­­­­­­doc.text);}

Map Function

key value docID

“2013-03-12” “ziplocks” “doc17”

“2013-09-30” “milk” “doc62”

“2013-10-17” “cat food” “doc82”

“2013-10-17” “tea bags” “doc83”

“2013-10-22” “eggs” “doc90”View Index

Views

• Map/Reduce mechanism­ A standard method of indexing in NoSQL ­ A view is similar to index in relational database.

• App-defined map function­ Called on every document­ Can emit arbitrary key/value pairs into the index

• Optional reduce function­ Data aggregation / grouping

• Functions are registered as native callbacks­ Native callbacks make sense for performance and to match the rest of

the app codebase

Putting the “No” in NoSQL

Creating a Database View

// Define a view with a map function that indexes to-do items by creation date: db = manager.getDatabase(DATABASE_NAME); View view = db.getView(String.format("%s/%s", dDocName, byDateViewName)); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { Object createdAt = document.get("created_at"); if(createdAt != null) { emitter.emit(createdAt.toString(), document); } } }, "1.0");

Not­a­UIView­—a­database­“view”is­like­an­index.

1

2

3

4

Queries and LiveQueries

Queries

• Basic feature set­ Key ranges, offset/limit, reverse, group by key…­ No joins or fancy sorting­ but compound keys (and clever emits) allow for some tricks

• LiveQuery subclass­ Monitors a view for changes­ Can think of it as a “pub-sub” approach­ Register a callback that is triggered when the query changes

Live Queries & UI

key value docID

“2013-09-30” “soy milk” “doc62”

“2013-10-17” “egg whites” “doc82”

“2013-10-17” “chocolate” “doc83”

view­index

data­source

ArrayAdapter

LiveQuery

Query}

Driving the Table from a View Query- define ArrayAdapter

public class GrocerySyncArrayAdapter extends ArrayAdapter<QueryRow> {

public View getView(int position, View itemView, ViewGroup parent) { if (itemView == null) { … // inflate layout }

TextView label = ((ViewHolder)itemView.getTag()).label; QueryRow row = getItem(position); SavedRevision currentRevision = row.getDocument().getCurrentRevision(); boolean itemChecked = ((Boolean) currentRevision.getProperty("check")).booleanValue(); String groceryItemText = (String) currentRevision.getProperty("text"); label.setText(groceryItemText);

… // set checkbox image based on isGroceryItemChecked return itemView;}

1

2

3

4

5

Driving the Table from a View Query - refreshing array adapter

liveQuery = view.createQuery().toLiveQuery();liveQuery.addChangeListener(new LiveQuery.ChangeListener() { public void changed(final LiveQuery.ChangeEvent event) { runOnUiThread(new Runnable() { public void run() { grocerySyncArrayAdapter.clear(); for (Iterator<QueryRow> it = event.getRows(); it.hasNext();) { grocerySyncArrayAdapter.add(it.next()); } grocerySyncArrayAdapter.notifyDataSetChanged(); progressDialog.dismiss(); } }); }});liveQuery.start();

1

2

3

4

5

6

Responding to Taps — toggle checkbox

public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

QueryRow row = (QueryRow) adapterView.getItemAtPosition(position); Document document = row.getDocument(); Map<String, Object> props = new HashMap<String, Object>(document.getProperties());

boolean checked = ((Boolean) props.get("check")).booleanValue(); props.put("check", !checked);

document.putProperties(props); itemListViewAdapter.notifyDataSetChanged();

}

1

2

3

4

6

5

7

Adding New Items

Document document = database.createDocument();

Map<String, Object> properties = new HashMap<String, Object>();properties.put("text", text);properties.put("check", Boolean.FALSE);properties.put("created_at", currentTimeString);document.putProperties(properties);

return document;

1

3

2

Sync

Sync Architecture

Sync Gateway (Cloud)

PushReplication

PullReplication

Couchbase Server (Cloud)

Your App

CallbackNotifications

Runs in sameprocess as your app

Replication

• Each Replication is one-directional (push or pull)

• Replications can be one-shot or continuous­ One-shot: Stops when complete.­ Continuous: Keeps monitoring changes till app quits

• Replicator runs in a background thread­ It detects online/offline, handles connection errors, retries…­ You just see document-changed or query-changed notifications.

• Progress is observable through a change listener

Filtered Replication

• Filtered pull

• Grocery Sync - guest

• Todo Lite - facebook auth

• Filtered push: You can define a filter function to control which documents are pushed to the Sync Gateway.

Creating Replications

URL syncUrl; try { syncUrl = new URL(SYNC_URL); } catch (MalformedURLException e) { throw new RuntimeException(e); }

Replication pullReplication = database.createPullReplication(syncUrl); pullReplication.setContinuous(true);

Replication pushReplication = database.createPushReplication(syncUrl); pushReplication.setContinuous(true);

pullReplication.addChangeListener(this); pushReplication.addChangeListener(this);

pullReplication.start(); pushReplication.start();

1

2

3

4

Monitoring Replications

public void changed(Replication.ChangeEvent event) {

Replication replication = event.getSource(); Log.d(TAG, "Replication : " + replication + " changed."); if (!replication.isRunning()) { String msg = String.format("Replicator %s not running", replication); Log.d(TAG, msg); } else { int processed = replication.getCompletedChangesCount(); int total = replication.getChangesCount(); String msg = String.format("Replicator processed %d / %d", processed, total); Log.d(TAG, msg); }

}

1

2

3

How to get started

How to get started

• Play with the demo apps• Grocery Sync

• TodoLite-Android (Facebook auth, Channels, Attachments, Sharing)

• Install Sync Gateway• Grocery Sync

• TodoLite couchbase cloud

• Create your own app • Add Maven dependencies

• Or add source code directly

Check out our Developer portal

• Total documentation revamp

Developer Portal - Native API reference

Developer Portal - Guides

Developer Portal - REST API Reference

Announcement New in 1.0 Release:

Portable Java

• Couchbase lite now runs on Java

• Linux, OSX, Windows

Join the Couchbase Lite open source community

• Official homepage with downloads­ mobile.couchbase.com

• Developer portal - documentation­ http://developer.couchbase.com

• Google Group (active community)­ https://groups.google.com/forum/?fromgroups#!forum/mobile-couchbase

• All code is open source on Github­ https://github.com/couchbase/couchbase-lite-android

Upcoming webinars

• Couchbase Lite iOS (June 10th)

• A Deep Dive into Couchbase Mobile (June 17th)

• Sync Gateway Configuration and Management (June 24th)

Thanks for watching!

Contact: tleyden@couchbase.com

Questions?

Recommended