webinar - developing with couchbase lite on android

50
Developing With Couchbase Lite on Android Traun Leyden [email protected] 10/29/13

Upload: couchbase

Post on 28-Jun-2015

943 views

Category:

Technology


4 download

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

TRANSCRIPT

Page 1: Webinar - Developing with Couchbase lite on Android

Developing WithCouchbase Lite on Android

Traun [email protected]

10/29/13

Page 2: Webinar - Developing with Couchbase lite on Android

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

Page 3: Webinar - Developing with Couchbase lite on Android

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

Page 4: Webinar - Developing with Couchbase lite on Android
Page 5: Webinar - Developing with Couchbase lite on Android
Page 6: Webinar - Developing with Couchbase lite on Android
Page 7: Webinar - Developing with Couchbase lite on Android
Page 8: Webinar - Developing with Couchbase lite on Android

For more information

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

mand-May.html

Page 9: Webinar - Developing with Couchbase lite on Android

Couchbase Lite on Android

• Installation and setup walk-through

• Demo of Grocery Sync sample app

• Tour of Grocery Sync code

Page 10: Webinar - Developing with Couchbase lite on Android

Installation setup and walk-through

• Clone the GrocerySync-Android repository

• Import into Android Studio

• Build & Run

Page 11: Webinar - Developing with Couchbase lite on Android

1. Clone the GrocerySync-Android repository

$ git clone [email protected]:couchbaselabs/GrocerySync-Android.git

Page 12: Webinar - Developing with Couchbase lite on Android

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.

Page 13: Webinar - Developing with Couchbase lite on Android

Import into Android Studio 0.5.7or later

Choose Import Project ..

Page 14: Webinar - Developing with Couchbase lite on Android

Import into Android StudioChoose the folder

you did the git clone into

Page 15: Webinar - Developing with Couchbase lite on Android

Build and Run

Hit the Run button to launch

the app

Page 16: Webinar - Developing with Couchbase lite on Android

Build and Run

The emulator will launch runningGrocery Sync

Page 17: Webinar - Developing with Couchbase lite on Android

Live Demo

Page 18: Webinar - Developing with Couchbase lite on Android

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

• Verified that documents were Sync’d between devices

• Demo conflict resolution

Page 19: Webinar - Developing with Couchbase lite on Android

A Tour of the Codeand the API

Page 20: Webinar - Developing with Couchbase lite on Android

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

Page 21: Webinar - Developing with Couchbase lite on Android

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

Page 22: Webinar - Developing with Couchbase lite on Android

Manager

• Collection of named databases

• Typically you will use a single manager

• Manages database storage (local directory)

Page 23: Webinar - Developing with Couchbase lite on Android

Database

• Not a wrapper for a cloud service

• Namespace for documents

• Contains views and their indexes

• Contains validation functions

• Source and target of replication

Page 24: Webinar - Developing with Couchbase lite on Android

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

Page 25: Webinar - Developing with Couchbase lite on Android

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

Page 26: Webinar - Developing with Couchbase lite on Android

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

Page 27: Webinar - Developing with Couchbase lite on Android

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

Page 28: Webinar - Developing with Couchbase lite on Android

Queries and LiveQueries

Page 29: Webinar - Developing with Couchbase lite on Android

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

Page 30: Webinar - Developing with Couchbase lite on Android

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}

Page 31: Webinar - Developing with Couchbase lite on Android

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

Page 32: Webinar - Developing with Couchbase lite on Android

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

Page 33: Webinar - Developing with Couchbase lite on Android

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

Page 34: Webinar - Developing with Couchbase lite on Android

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

Page 35: Webinar - Developing with Couchbase lite on Android

Sync

Page 36: Webinar - Developing with Couchbase lite on Android

Sync Architecture

Sync Gateway (Cloud)

PushReplication

PullReplication

Couchbase Server (Cloud)

Your App

CallbackNotifications

Runs in sameprocess as your app

Page 37: Webinar - Developing with Couchbase lite on Android

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

Page 38: Webinar - Developing with Couchbase lite on Android

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.

Page 39: Webinar - Developing with Couchbase lite on Android

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

Page 40: Webinar - Developing with Couchbase lite on Android

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

Page 41: Webinar - Developing with Couchbase lite on Android

How to get started

Page 42: Webinar - Developing with Couchbase lite on Android

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

Page 43: Webinar - Developing with Couchbase lite on Android

Check out our Developer portal

• Total documentation revamp

Page 44: Webinar - Developing with Couchbase lite on Android

Developer Portal - Native API reference

Page 45: Webinar - Developing with Couchbase lite on Android

Developer Portal - Guides

Page 46: Webinar - Developing with Couchbase lite on Android

Developer Portal - REST API Reference

Page 47: Webinar - Developing with Couchbase lite on Android

Announcement New in 1.0 Release:

Portable Java

• Couchbase lite now runs on Java

• Linux, OSX, Windows

Page 48: Webinar - Developing with Couchbase lite on Android

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

Page 49: Webinar - Developing with Couchbase lite on Android

Upcoming webinars

• Couchbase Lite iOS (June 10th)

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

• Sync Gateway Configuration and Management (June 24th)

Page 50: Webinar - Developing with Couchbase lite on Android

Thanks for watching!

Contact: [email protected]

Questions?