+ All Categories
Home > Software > Firebase with Android

Firebase with Android

Date post: 07-Jan-2017
Category:
Upload: fumihiko-shiroyama
View: 905 times
Download: 3 times
Share this document with a friend
85
Firebase with Android GCPUG TOKYO MARCH 2016
Transcript
Page 1: Firebase with Android

Firebase with Android

GCPUG TOKYO MARCH 2016

Page 2: Firebase with Android

Firebase

Page 3: Firebase with Android

Firebase

• Realtime Database

• Authentication & Access Control

• Static Web Site Hosting

Page 4: Firebase with Android

Udacity

• Firebase Essential For Android

• https://www.udacity.com/course/firebase-essentials-for-android--ud009

Page 5: Firebase with Android

Getting Started

Page 6: Firebase with Android

www.firebase.com

Page 7: Firebase with Android
Page 8: Firebase with Android
Page 9: Firebase with Android
Page 10: Firebase with Android

dependencies { compile 'com.firebase:firebase-client-android:2.5.2+'}

Page 11: Firebase with Android

android { ... packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' }}

Page 12: Firebase with Android

<uses-permission android:name="android.permission.INTERNET" />

Page 13: Firebase with Android

Custom Application

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } }

Page 14: Firebase with Android

AndroidManifest.xml

<application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">

Page 15: Firebase with Android

Writing Data

Page 16: Firebase with Android

AndroidManifest.xml

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").setValue("hello firebase!");

Page 17: Firebase with Android

Activity

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").setValue("hello firebase!");

Reference

Page 18: Firebase with Android

Activity

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").setValue("hello firebase!");

Child Node

Page 19: Firebase with Android

Activity

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").setValue("hello firebase!");

Writing

Page 20: Firebase with Android
Page 21: Firebase with Android

Not Limited to Primitive Types

Page 22: Firebase with Android

public class BlogPost { private String author; private String title;

public BlogPost() { // empty default constructor

// necessary for Firebase to be able to deserialize blog posts }

public String getAuthor() { return author;

}

public String getTitle() { return title; }}

Page 23: Firebase with Android

Understating Data Structure

Page 24: Firebase with Android

NoSQL JSON Tree{ "users": { "mchen": { "friends": { "brinchen": true }, "name": "Mary Chen", // our child node appears in the existing JSON tree "widgets": { "one": true, "three": true } }, "brinchen": { ... }, "hmadi": { ... } }}

Page 25: Firebase with Android

NoSQL JSON Tree{ "users": { "mchen": { "friends": { "brinchen": true }, "name": "Mary Chen", // our child node appears in the existing JSON tree "widgets": { "one": true, "three": true } }, "brinchen": { ... }, "hmadi": { ... } }}

Page 26: Firebase with Android

NoSQL JSON Tree{ "users": { "mchen": { "friends": { "brinchen": true }, "name": "Mary Chen", // our child node appears in the existing JSON tree "widgets": { "one": true, "three": true } }, "brinchen": { ... }, "hmadi": { ... } }}

/users/mchen/widgets

Page 27: Firebase with Android

NoSQL JSON Tree{ "users": { "mchen": { "friends": { "brinchen": true }, "name": "Mary Chen", // our child node appears in the existing JSON tree "widgets": { "one": true, "three": true } }, "brinchen": { ... }, "hmadi": { ... } }}

/users/mchen/widgets

Unique Identifier

Page 28: Firebase with Android

Valid Types

Page 29: Firebase with Android

• String

• Boolean

• Long

• Double

• Map<String, Object>

• List<Object>

Page 30: Firebase with Android

Retrieving Data

Page 31: Firebase with Android

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Toast.makeText( MainActivity.this, dataSnapshot.getValue(String.class), Toast.LENGTH_SHORT ).show(); } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 32: Firebase with Android

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Toast.makeText( MainActivity.this, dataSnapshot.getValue(String.class), Toast.LENGTH_SHORT ).show(); } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 33: Firebase with Android

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Toast.makeText( MainActivity.this, dataSnapshot.getValue(String.class), Toast.LENGTH_SHORT ).show(); } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 34: Firebase with Android

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Toast.makeText( MainActivity.this, dataSnapshot.getValue(String.class), Toast.LENGTH_SHORT ).show(); } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 35: Firebase with Android

Firebase firebaseRef = new Firebase("https://shiroyama-app-01.firebaseio.com/"); firebaseRef.child("message").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Toast.makeText( MainActivity.this, dataSnapshot.getValue(String.class), Toast.LENGTH_SHORT ).show(); } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 36: Firebase with Android

Read Event Types

Page 37: Firebase with Android

• Value

• Child Added

• Child Changed

• Child Removed

• Child Moved

Page 38: Firebase with Android

Value Event

• ValueEventListener#onDataChange

• Retrieve whole data at once

• Called once at initial time, then every time data changes.

Page 39: Firebase with Android

// Get a reference to our postsFirebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");// Attach an listener to read the data at our posts referenceref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println("There are " + snapshot.getChildrenCount() + " blog posts"); for (DataSnapshot postSnapshot: snapshot.getChildren()) { BlogPost post = postSnapshot.getValue(BlogPost.class); System.out.println(post.getAuthor() + " - " + post.getTitle()); } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); }});

Page 40: Firebase with Android

// Get a reference to our postsFirebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");// Attach an listener to read the data at our posts referenceref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println("There are " + snapshot.getChildrenCount() + " blog posts"); for (DataSnapshot postSnapshot: snapshot.getChildren()) { BlogPost post = postSnapshot.getValue(BlogPost.class); System.out.println(post.getAuthor() + " - " + post.getTitle()); } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); }});

Page 41: Firebase with Android

// Get a reference to our postsFirebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");// Attach an listener to read the data at our posts referenceref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println("There are " + snapshot.getChildrenCount() + " blog posts"); for (DataSnapshot postSnapshot: snapshot.getChildren()) { BlogPost post = postSnapshot.getValue(BlogPost.class); System.out.println(post.getAuthor() + " - " + post.getTitle()); } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); }});

Page 42: Firebase with Android

Child Added Event

• ChildEventListener#onChildAdded

• Once for each existing child initially

• Every time new data is added

Page 43: Firebase with Android

// Get a reference to our postsFirebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");

ref.addChildEventListener(new ChildEventListener() { // Retrieve new posts as they are added to the database @Override public void onChildAdded(DataSnapshot snapshot, String previousChildKey) { BlogPost newPost = snapshot.getValue(BlogPost.class); System.out.println("Author: " + newPost.getAuthor()); System.out.println("Title: " + newPost.getTitle()); }

//... ChildEventListener also defines onChildChanged, onChildRemoved, // onChildMoved and onCanceled, covered in later sections.});

Page 44: Firebase with Android

Child Changed Event

• ChildEventListener#onChildChanged

• Anytime a child is changed including its descendants

Page 45: Firebase with Android

@Overridepublic void onChildChanged(DataSnapshot snapshot, String previousChildKey) { String title = (String) snapshot.child("title").getValue(); System.out.println("The updated post title is " + title);}

Page 46: Firebase with Android

Child Removed Event

• ChildEventListener#onChildRemoved

• Anytime a child is removed

Page 47: Firebase with Android

@Overridepublic void onChildRemoved(DataSnapshot snapshot) { String title = (String) snapshot.child("title").getValue(); System.out.println("The blog post titled " + title + " has been deleted");}

Page 48: Firebase with Android

Child Moved Event

• ChildEventListener#onChildMoved

• Anytime a child is moved

Page 49: Firebase with Android

@Overridepublic void onChildMoved(DataSnapshot snapshot, String previousChildKey) { String title = (String) snapshot.child("title").getValue(); System.out.println("The updated post title is " + title);}

Page 50: Firebase with Android

Detaching Callbacks

• ref.removeEventListener(originalListener);

• all listeners must be removed explicitly

• removing parent listener will NOT remove child's listeners

Page 51: Firebase with Android

Reading Data Once

Page 52: Firebase with Android

ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // do some stuff once } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 53: Firebase with Android

ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // do some stuff once } @Override public void onCancelled(FirebaseError firebaseError) { }});

Page 54: Firebase with Android

Querying Data

Page 55: Firebase with Android

{ "lambeosaurus": { "height" : 2.1, "length" : 12.5, "weight": 5000 }, "stegosaurus": { "height" : 4, "length" : 9, "weight" : 2500 }}

Page 56: Firebase with Android

public class DinosaurFacts { long height; double length; long weight;

public DinosaurFacts() { // empty default constructor // necessary for Firebase to be able to deserialize blog posts }

public long getHeight() { return height; }

public double getLength() { return length; }

public long getWeight() { return weight; }}

Page 57: Firebase with Android

• orderByChild()

• orderByKey()

• orderByValue()

• orderByPriority()

Page 58: Firebase with Android

orderByChild

Query queryRef = ref.orderByChild("height");orQuery queryRef = ref.orderByChild("dimensions/height");

Page 59: Firebase with Android

orderByKey

Query queryRef = ref.orderByKey();

{ "lambeosaurus": { "height" : 2.1, "length" : 12.5, "weight": 5000 }, "stegosaurus": { "height" : 4, "length" : 9, "weight" : 2500 }}

Page 60: Firebase with Android

orderByValue

Query queryRef = ref.orderByValue();

{ "scores": { "bruhathkayosaurus" : 55, "lambeosaurus" : 21, "linhenykus" : 80, "pterodactyl" : 93, "stegosaurus" : 5, "triceratops" : 22 }}

Page 61: Firebase with Android

orderByPriority

Query queryRef = ref.orderByPriority();

Page 62: Firebase with Android

orderByPriority

Query queryRef = ref.orderByPriority();

arbitrary priority you set

Page 63: Firebase with Android

• limitToFirst()

• limitToLast()

• startAt()

• endAt()

• equalTo()

Page 64: Firebase with Android

Query queryRef = ref.orderByChild("height").limitToFirst(2);Query queryRef = scoresRef.orderByValue().limitToLast(3);Query queryRef = ref.orderByChild("height").startAt(3);Query queryRef = ref.orderByKey().endAt("pterodactyl");Query queryRef = ref.orderByChild("height").equalTo(25);

Page 65: Firebase with Android

Security

Page 66: Firebase with Android
Page 67: Firebase with Android

{ "rules": { "users": { "$user_id": { ".write": "$user_id === auth.uid" } } }}

Page 68: Firebase with Android

{ "rules": { "users": { "$user_id": { ".write": "$user_id === auth.uid" } } }}

Page 69: Firebase with Android

{ "rules": { "users": { "$user_id": { ".write": "$user_id === auth.uid" } } }} talks about this later

Page 70: Firebase with Android

Authentication

Page 71: Firebase with Android

Custom

Page 72: Firebase with Android

• helper libraries to integrate with your own authentications

• https://www.firebase.com/docs/android/guide/login/custom.html#section-rest-token-helper-libraries

Page 73: Firebase with Android

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");ref.authWithCustomToken(AUTH_TOKEN, new Firebase.AuthResultHandler() { @Override public void onAuthenticationError(FirebaseError error) { System.err.println("Login Failed! " + error.getMessage()); }

@Override public void onAuthenticated(AuthData authData) { System.out.println("Login Succeeded!"); }});

Page 74: Firebase with Android

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");ref.authWithCustomToken(AUTH_TOKEN, new Firebase.AuthResultHandler() { @Override public void onAuthenticationError(FirebaseError error) { System.err.println("Login Failed! " + error.getMessage()); }

@Override public void onAuthenticated(AuthData authData) { System.out.println("Login Succeeded!"); }});

Page 75: Firebase with Android

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");ref.authWithCustomToken(AUTH_TOKEN, new Firebase.AuthResultHandler() { @Override public void onAuthenticationError(FirebaseError error) { System.err.println("Login Failed! " + error.getMessage()); }

@Override public void onAuthenticated(AuthData authData) { System.out.println("Login Succeeded!"); }});

given from your server

Page 76: Firebase with Android

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");ref.authWithCustomToken(AUTH_TOKEN, new Firebase.AuthResultHandler() { @Override public void onAuthenticationError(FirebaseError error) { System.err.println("Login Failed! " + error.getMessage()); }

@Override public void onAuthenticated(AuthData authData) { System.out.println("Login Succeeded!"); }});

Page 77: Firebase with Android

• javadoc

• https://www.firebase.com/docs/java-api/javadoc/com/firebase/client/AuthData.html

• AuthData#getUid()

Unique Guaranteed

Page 78: Firebase with Android

Tips

Page 79: Firebase with Android

• SwipeRefresh should be used with ValueEvent(once)

Page 80: Firebase with Android

Limitations

Page 81: Firebase with Android

• No File Uploading APIs

• Server side batching

• Server side scheduling

• Server side event hook

Page 82: Firebase with Android

Q & A

Page 83: Firebase with Android

Samples

Page 84: Firebase with Android

• Chat

• https://github.com/firebase/AndroidChat

• Drawing

• https://github.com/firebase/AndroidDrawing

Page 85: Firebase with Android

THX!


Recommended