Your SlideShare is downloading. ×

Webinar - Developing with Couchbase lite on Android

884

Published on

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, …

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
884
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
16
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Developing With Couchbase Lite on Android Traun Leyden tleyden@couchbase.com 10/29/13
  • 2. 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
  • 3. 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
  • 4. For more information • See Couchbase Mobile Overview Webinar - http://info.couchbase.com/couchbase-mobile-webinar-overview-on- demand-May.html
  • 5. Couchbase Lite on Android • Installation and setup walk-through • Demo of Grocery Sync sample app • Tour of Grocery Sync code
  • 6. Installation setup and walk-through • Clone the GrocerySync-Android repository • Import into Android Studio • Build & Run
  • 7. 1. Clone the GrocerySync-Android repository $ git clone git@github.com:couchbaselabs/GrocerySync- Android.git
  • 8. 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.
  • 9. Import into Android Studio 0.5.7 or later Choose Import Project
  • 10. Import into Android Studio Choose the folder you did the git clone into
  • 11. Build and Run Hit the Run button to launch the app
  • 12. Build and Run The emulator will launch running Grocery Sync
  • 13. Live Demo
  • 14. Demo Recap • We were able to create, update, and delete records • Verified that documents were Sync’d between devices • Demo conflict resolution
  • 15. A Tour of the Code and the API
  • 16. 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
  • 17. 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
  • 18. Manager • Collection of named databases • Typically you will use a single manager • Manages database storage (local directory)
  • 19. Database • Not a wrapper for a cloud service • Namespace for documents • Contains views and their indexes • Contains validation functions • Source and target of replication
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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"); 1 2 3 4
  • 24. Queries and LiveQueries
  • 25. 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
  • 26. Live Queries & UI key value docID “2013-09-30” “soy milk” “doc62” “2013-10-17” “egg whites” “doc82” “2013-10-17” “chocolate” “doc83” ArrayAdapte r LiveQuery Query }
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. Sync
  • 32. Sync Architecture Sync Gateway (Cloud) Push Replication Pull Replication Couchbase Server (Cloud) Your App Callback Notifications Runs in same process as your app
  • 33. 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
  • 34. 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.
  • 35. 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
  • 36. 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
  • 37. How to get started
  • 38. 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
  • 39. Check out our Developer portal • Total documentation revamp
  • 40. Developer Portal - Native API reference
  • 41. Developer Portal - Guides
  • 42. Developer Portal - REST API Reference
  • 43. Announcement New in 1.0 Release: Portable Java • Couchbase lite now runs on Java • Linux, OSX, Windows
  • 44. 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
  • 45. Upcoming webinars • Couchbase Lite iOS (June 10th) • A Deep Dive into Couchbase Mobile (June 17th) • Sync Gateway Configuration and Management (June 24th)
  • 46. Thanks for watching! Contact: tleyden@couchbase.com Questions?

×