Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Cloud Firestore on Android

Cloud Firestore on Android

An overview of Cloud Firestore and implementation on Android

Eoin Fogarty

May 19, 2019
Tweet

More Decks by Eoin Fogarty

Other Decks in Programming

Transcript

  1. # Introduction - Eoin Fogarty - Native Engineer at Cyberagent

    (REQU). - Android and Flutter developer @_modge_ https://github.com/eoinfogarty
  2. # What is Cloud Firestore Cloud Firestore is a flexible,

    scalable NoSQL cloud database to sync data for client and server-side development. Capabilities - Flexibility - Expressive Querying - Realtime Updates - Offline Support - Designed to Scale
  3. # NoSQL vs SQL SQL - Relational Databases (RDBMS); -

    Table based databases. - Tables which consists of n number of rows of data. - Predefined schema . - Vertically scalable NoSQL - Distributed database. - Document based, key-value pairs, graph databases or wide-column stores. - key-value pair, documents, graph databases or wide-column stores which do not have standard schema definitions which it needs to adhered to ie dynamic schema. - Dynamic schema for unstructured data. - Horizontially scalable
  4. # Data Models In Firestore there are no tables or

    rows. Data is stored in Documents and organized in Collections.
  5. # Documents - Stored in Collections - Contains a set

    of key-value pairs. - Can contain subcollections and nested objects. - Identified by a name. - Supports a variety of data-types eg boolean, string, number etc. - Complex objects can be represented with maps. Example: ❒ _modge_ name: first : "Eoin" last : "Fogarty" born : 1900
  6. # Collections - Simply a container for documents. - Cannot

    contain other collections. - Do not create or delete, its implied. - Contained documents can contain different fields and types. Example: ❒❒ users ❒ _modge_ name: first : "Eoin" last : "Fogarty" ❒ heihei first : "Shawn" last : "Kawano"
  7. # Getting Started - Android 1 - Add Firebase to

    your Android app. 2 - In build.gradle make sure to add google maven repository. 3 - Add firestore dependency. implementation 'com.google.firebase:firebase-firestore-ktx:19.0.0' 4 - Initialize Cloud Firestore. val db = FirebaseFirestore.getInstance()
  8. # Add data To create or overwrite a document we

    use the set method val user = HashMap<String, Any>() user["name"] = "Eoin Fogarty" user["born"] = "1900" db.collection("users").document("_modge_") .set(user) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify otherwise
  9. # Read Data Once We can use the get() method

    to retrieve an entire collection db.collection("users") .get() .addOnSuccessListener { result -> for (document in result) { Log.d(TAG, "${document.id} => ${document.data}") } } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents.", exception) }
  10. # Realtime Updates We can listen to a document with

    the onSnapshot() method. val docRef = db.collection("users").document("_modge_") docRef.addSnapshotListener(EventListener<DocumentSnapshot> { snapshot, e -> if (e != null) { Log.w(TAG, "Listen failed.", e) return@EventListener } if (snapshot != null && snapshot.exists()) { Log.d(TAG, "Current data: ${snapshot.data}") } else { Log.d(TAG, "Current data: null") } })
  11. # Securing Data All Cloud Firestore Security Rules consist of

    match statements, which identify documents in your database, and allow expressions, which control access to those documents: // Allow read/write access on all documents to any user signed in to the application service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth.uid != null; } } }
  12. # Extending with Cloud Functions With Cloud Functions, you can

    deploy Node.js code to handle events triggered by changes in your Cloud Firestore database. The Cloud Functions for Firebase SDK exports a functions.firestore object that allows you to create handlers tied to specific events. - onCreate: when a document is written to for the first time. - onUpdate: when a document already exists and has a value changed. - onDelete: when a document with data is deleted. - onWrite: when onCreate, onUpdate or onDelete is triggered.
  13. # Extending with Cloud Functions This will trigger a function

    to fire any time a new document is created in a collection by using an onCreate() handler with a wildcard exports.createUser = functions.firestore .document('users/{userId}') .onCreate((snap, context) => { // Get an object representing the document // e.g. {'name': 'Eoin', 'age': 119} const newValue = snap.data(); // access a particular field as you would any JS property const name = newValue.name; // perform desired operations eg send push... });
  14. # Much More - Simple and compound queries - Order

    and limit data - Paginate Data - Offline Data Access - Indexes - Transactions and batched writes - Conditional Security Rules - Testing security rules