SlideShare ist ein Scribd-Unternehmen logo
1 von 104
Google Firebase
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (G-02)
Firebase2
Firebase Realtime
Database
Store and sync data in real time across all connected clients
3
Firebase Realtime Database
▹ The Firebase Realtime Database is a cloud-hosted
database.
▹ Data is stored as JSON and synchronized in realtime
to every connected client.
▹ When you build cross-platform apps with our iOS,
Android, and JavaScript SDKs, all of your clients
share one Realtime Database instance and
automatically receive updates with the newest
data.
4
Firebase Realtime Database-
KEY CAPABILITIES
Realtime
Instead of typical HTTP requests, the
Firebase Realtime Database uses data
synchronization—every time data
changes, any connected device
receives that update within
milliseconds. Provide collaborative
and immersive experiences without
thinking about networking code.
Offline
Firebase apps remain responsive even
when offline because the Firebase
Realtime Database SDK persists your
data to disk. Once connectivity is
reestablished, the client device
receives any changes it missed,
synchronizing it with the current
server state.
5
Firebase Realtime Database-
KEY CAPABILITIES
Accessible from Client Devices
The Firebase Realtime Database can be accessed directly from a mobile
device or web browser; there’s no need for an application server. Security and
data validation are available through the Firebase Realtime Database Security
Rules, expression-based rules that are executed when data is read or written.
6
Example
7
Firebase
Authentication
Authenticate and manage users from a variety of providers without server-side
code
8
Firebase Authentication
▹ Firebase Authentication provides backend services,
easy-to-use SDKs, and ready-made UI libraries to
authenticate users to your app.
▹ It supports authentication using passwords,
popular federated identity providers like Google,
Facebook and Twitter, and more.
9
Firebase Authentication -
KEY CAPABILITIES
FirebaseUI (beta)
The FirebaseUI Auth component
implements best practices for
authentication on mobile devices and
websites, which can maximize sign-in
and sign-up conversion for your app.
It also handles edge cases like
account recovery and account linking
that can be security sensitive and
error-prone to handle correctly
Email and password based
authentication
Authenticate users with their email
addresses and passwords. The
Firebase Authentication SDK provides
methods to create and manage users
that use their email addresses and
passwords to sign in. Firebase
Authentication also handles sending
password reset emails.
10
Firebase Authentication -
KEY CAPABILITIES
Federated identity provider
integration
Authenticate users by integrating with
federated identity providers. The
Firebase Authentication SDK provides
methods that allow users to sign in
with their Google, Facebook, Twitter,
and GitHub accounts.
Custom auth system integration
Connect your app's existing sign-in
system to the Firebase Authentication
SDK and gain access to Firebase
Realtime Database and other Firebase
services.
11
Firebase Authentication -
KEY CAPABILITIES
Anonymous auth
Use Firebase features that require
authentication without requiring
users to sign in first by creating
temporary anonymous accounts. If
the user later chooses to sign up, you
can upgrade the anonymous account
to a regular account, so the user can
continue where they left off.
12
Example
13
Firebase Cloud
Messaging
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets
you reliably deliver messages at no cost.
14
Firebase Cloud Messaging
▹ Using FCM, you can notify a client app that new
email or other data is available to sync. You can
send notification messages to drive user
reengagement and retention.
▹ For use cases such as instant messaging, a message
can transfer a payload of up to 4KB to a client app.
15
Firebase Cloud Messaging -
KEY CAPABILITIES
Send notification messages or data
messages
Send notification messages that are
displayed to your user. Or send data
messages and determine completely
what happens in your application
code.
Versatile message targeting
Distribute messages to your client app
in any of three ways — to single
devices, to groups of devices, or to
devices subscribed to topics.
16
Firebase Cloud Messaging -
KEY CAPABILITIES
Send messages from client apps
Send acknowledgments, chats, and
other messages from devices back to
your server over FCM’s reliable and
battery-efficient connection channel..
17
Firebase
Notifications
Firebase Notifications is a free service that enables targeted user notifications for
mobile app developers.
18
Firebase Notifications
▹ Built on Firebase Cloud Messaging and the FCM
SDK, Firebase Notifications (Notifications) provides
an option for developers and organizations seeking
a flexible notification platform that requires
minimal coding effort to get started, and a
graphical console for sending messages.
▹ Using the Notifications console GUI, you can
reengage and retain your userbase, foster app
growth, and support marketing campaigns.
19
Firebase Notifications- KEY
CAPABILITIES
Notifications analytics
Analyze reengagement conversion
with built-in notifications analytics
collection and funnel analysis.
Versatile message targeting
Target clients in predefined user
segments, custom analytics
audiences, clients subscribed to
topics, and single devices.
20
Firebase Notifications- KEY
CAPABILITIES
Flexible message scheduling
Deliver notifications (up to 2kb)
immediately, or at a future time in the
client's local time
21
Firebase Storage
Store and retrieve user-generated content such as images, audio and video without
server-side code
22
Firebase Storage
▹ Firebase Storage adds Google security to file
uploads and downloads for your Firebase apps,
regardless of network quality.
▹ You can use it to store images, audio, video, or
other user-generated content.
▹ Firebase Storage is backed by Google Cloud
Storage, a powerful, simple, and cost-effective
object storage service.
23
Firebase Storage - KEY
CAPABILITIES
Robust operations
Firebase Storage
performs uploads and
downloads regardless
of network quality.
Uploads and downloads
are robust, meaning
they restart where they
stopped, saving your
users time and
bandwidth.
Strong security
Firebase Storage
integrates with Firebase
Authentication to
provide simple and
intuitive authentication
for developers. You can
use our declarative
security model to allow
access based on
filename, size, content
type, and other
High scalability
Firebase Storage is
backed by Google Cloud
Storage for petabyte
scale when your app
goes viral. Effortlessly
grow from prototype to
production using the
same infrastructure that
powers Snapchat.
24
Firebase Hosting
Deploy web and mobile web apps in seconds using a secure global content delivery
network
25
Firebase Hosting
▹ Firebase Hosting is production-grade web content
hosting for developers.
▹ With Hosting, you can quickly and easily deploy
web apps and static content to a global content-
delivery network (CDN) with a single command.
26
KEY CAPABILITIES
Served over a secure connection
The modern web is secure. Zero-
configuration SSL is built into
Firebase Hosting so content is
always delivered securely.
Fast content delivery
Each file you upload is cached on
SSDs at CDN edges around the world.
No matter where your users are, the
content is delivered fast.
27
KEY CAPABILITIES
Rapid deployment
Using the Firebase CLI, you can get
your app up and running in seconds.
Command line tools make it easy to
add deployment targets into your
build process.
One-click rollbacks
Quick deployments are great, but
being able to undo mistakes is even
better. Firebase Hosting provides full
versioning and release management
with one-click rollbacks.
28
Firebase Test Lab
for Android
Test your Android apps against a wide range of physical devices
29
Firebase Test Lab
▹ Firebase Test Lab for Android provides cloud-based
infrastructure for testing Android apps.
▹ With one operation, you can initiate testing of your
app across a wide variety of devices and device
configurations.
30
Firebase Test Lab
▹ Test results—including logs, videos, and
screenshots—are made available in your project in
the Firebase console.
▹ Even if you haven't written any test code for your
app, Test Lab can exercise your app automatically,
looking for crashes.
31
Firebase Test Lab - KEY
CAPABILITIES
Test on real devices
Use Test Lab to exercise your app on
devices installed and running in a
Google data center. Test Lab helps
you to find issues that only occur on
specific device configurations (for
example, a Nexus 5 running a specific
Android API level and specific locale
settings).
Run app tests, even if you haven't
written any
You can use Robo test to find issues
with your app so you can test your
app even if you haven't written app
tests. Robo test analyzes the
structure of your app's user interface
and then explores it, automatically
simulating user activities. If you have
written instrumentation tests for
your app, Test Lab can also run those
tests.
32
Firebase Test Lab - KEY
CAPABILITIES
Workflow integration
Test Lab is integrated with Android
Studio, the Firebase console, and the
gcloud command line. You can also
use Test Lab with Continuous
Integration (CI) systems.
33
Firebase Crash
Reporting
Get actionable insights and comprehensive analytics whenever your app crashes or
stops working.
34
Firebase Crash Reporting
▹Crash Reporting creates detailed reports of the
errors in your app.
▹Errors are grouped into clusters of similar stack
traces and triaged by the severity of impact on your
users.
▹In addition to automatic reports, you can log custom
events to help capture the steps leading up to a crash.
35
Firebase Crash Reporting-
KEY CAPABILITIES
Monitor fatal and non-fatal errors
Monitor fatal errors in iOS and fatal
and non-fatal errors in Android.
Reports are triaged by the severity of
impact on users.
Collect the data you need to
diagnose problems
Each report contains a full stack
trace as well as device
characteristics, performance data,
and user circumstances when the
error took place. Similar reports are
automatically clustered to make it
easier to identify related bugs.
36
Firebase Crash Reporting-
KEY CAPABILITIES
Integrate with Analytics
Errors captured are set as
app_exception events in Analytics,
allowing you to filter audiences
based on who sees errors.
Free and easy
Crash Reporting is free to use. Once
you've added Firebase to your app,
it's just a few lines of code to enable
comprehensive error reporting.
37
Example
38
Firebase Analytics
Get detailed analytics to measure and analyse how users engage with your app
39
FIREBASE ANALYTICS
▹a free and unlimited analytics tool built from the ground up
for mobile apps.
▹Firebase Analytics is at the core of the Firebase platform,
providing the insights you need to build successful apps.
▹Firebase Analytics helps you understand how your users
behave, so you can make informed decisions about how to
market your app.
40
FIREBASE ANALYTICS -
METRICS
▹average revenue per user
(ARPU),
▹active users,
▹retention reports,
▹event counts
▹combined with user properties
like device type, app version, and
OS version to give you insight into
how users interact with your app.
41
KEY CAPABILITIES
BigQuery
Link your Firebase Analytics app to
BigQuery where you can perform
custom analysis on your entire
Analytics dataset and import other
data sources.
Firebase Crash Reporting
Firebase Analytics logs events for
each crash so you can get a sense of
the rate of crashes for different
versions or regions, allowing you to
gain insight into which users are
impacted. You can also create
audiences for users who have
experienced multiple crashes and
respond with Firebase Notifications
directed at that audience.
42
KEY CAPABILITIES
Firebase Remote
Config
Use Firebase Analytics
audience definitions to
change the behavior
and appearance of your
app for different
audiences without
distributing multiple
versions of your app.
Google Tag Manager
Integrating Google Tag
Manager alongside
Firebase Analytics
enables you to manage
your Firebase Analytics
implementation
remotely from a web
interface after your app
has been distributed.
Firebase Notifications
Firebase Analytics
automatically logs
events that correspond
to your Firebase
Notifications and
supports reporting on
the impact of each
campaign.
43
Firebase Remote
Config
Customise and experiment with app behaviour using server-side configuration
parameters
44
Firebase Remote Config
▹Firebase Remote Config is a cloud service that lets you
change the behavior and appearance of your app without
requiring users to download an app update.
▹When using Remote Config, you create in-app default values
that control the behavior and appearance of your app.
▹Then, you can later use the Firebase console to override in-
app default values for all app users or for segments of your
userbase.
▹Your app controls when updates are applied, and it can
frequently check for updates and apply them with a negligible
impact on performance.
45
Firebase Remote Config -
KEY CAPABILITIES
Quickly roll out changes to your
app's userbase
You can make changes to your app's
default behavior and appearance by
changing server-side parameter
values. For example, you could
change your app's layout or color
theme to support a seasonal
promotion, with no need to publish
an app update.
Customize your app for segments
of your userbase
You can use Remote Config to
provide variations on your app's user
experience to different segments of
your userbase by app version, by
Firebase Analytics audience, by
language, and more.
46
Firebase Remote Config -
KEY CAPABILITIES
Run A/B tests to improve your app
You can use Remote Config random
percentile targeting with Firebase
Analytics to A/B test improvements
to your app across different
segments of your userbase so that
you can validate improvements
before rolling them out to your entire
userbase.
47
Example
48
Firebase App
Indexing
Firebase App Indexing gets your app into Google Search
49
Firebase Remote Config
▹Firebase App Indexing gets your app into Google Search. If
your Android app is already installed when users search for
related content, they will launch your app directly from Search
results.
▹If users don’t have your app yet, an install card shows up in
Search results for Android.
▹Adding App Indexing promotes both types of app results
within Google Search and also provides query autocompletions.
50
Example
51
AdMob
Earn more from your apps the smart way by showing ads from millions of Google
advertisers
52
AdMob
▹AdMob by Google is a mobile advertising platform that you
can use to generate revenue from your app.
▹Using AdMob with Firebase Analytics provides you with
additional app usage data and analytics capabilities.
▹Firebase integrates with AdMob without requiring changes to
your existing AdMob configuration.
53
AdMob - KEY CAPABILITIES
Earn more from AdMob's in-app
ads
Show ads from millions of Google
advertisers in real time, or use
AdMob Mediation to earn from over
40 premium networks through the
AdMob platform to simplify your ad
operations, improve competition,
and earn more, for free.
Improve user experience
Native and video ads create a
positive user experience as you
monetize by matching the look and
feel of your app. Choose from
different ad templates, customize
them, and experiment with different
layouts on the fly without
republishing your app.
54
AdMob - KEY CAPABILITIES
Scale fast
▹When your app's a global or
domestic hit, you can monetize users
quickly with AdMob, by showing ads
to users in more than 200 markets.
▹More than one app? AdMob house
ads is a free tool that enables you to
cross-promote your apps to your
userbase, across your family of apps.
Access monetization reports
AdMob is the premier monetization
platform for mobile. While
generating ad revenue, AdMob also
produces its own monetization
reports that you can use to make
smarter decisions about product
strategy.
55
Example
56
57
Take a Break
Firebase Setup
https://firebase.google.com/docs/android/setup
58
59
59
60
60
Firebase
Authentication
Authenticate and manage users from a variety of providers without server-side
code
61
Firebase – Instantiate62
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
// Initialize Firebase Auth and Database Reference
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mUserId = mFirebaseUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Firebase Authentication63
// initialize the FirebaseAuth instance
mFirebaseAuth = FirebaseAuth.getInstance();
//If a user has signed in successfully you can get their account data at any point
with the getCurrentUser method.
//get a FirebaseUser object, which contains information about the signed-in user.
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null) {
// Not logged in, launch the Log In activity
loadLogInView();
} else {
// User is signed in
mUserId = mFirebaseUser.getUid();
}
Firebase Authentication -
signup64
mFirebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(task.getException().getMessage())
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
Firebase Authentication -
signin65
mFirebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(LogInActivity.this, new
OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
GoToMainAvtivity();
} else
{
Toast.makeText(LogInActivity.this,"Error",Toast.LENGTH_SHORT).show();
}
}
});
Firebase Authentication -
SignOut66
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
mFirebaseAuth.signOut();
Intent intent = new Intent(MainActivity.this, LogInActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Firebase Authentication –
Check User Status67
if (mFirebaseUser == null) {
// go to loginpage
Intent intent = new Intent(MainActivity.this, LogInActivity.class);
startActivity(intent);
}
Firebase Authentication68
Firebase – Rules69
JSON
70
71 JSON
▹JSON (JavaScript Object Notation) is a lightweight data-
interchange format.
▸Data is in name/value pairs
▸Data is separated by commas ,
▸Curly braces hold objects { }
▸Square brackets hold arrays [ ]
71
72 Name/Value pairs
Name Value:
{ “Matrix No” : “A111111” }
73 JSON
▹JSON values can be:
▸A number (integer or floating point)
▸A string (in double quotes) “”
▸A Boolean (true or false)
▸An array (in square brackets) []
▸An object (in curly braces) {}
▸null
73
74 Name/Value pairs
Name Value:
{ “Matrix No” : “A111111” }
{ “Fees” : 500.00}
String Matrix No = “A111111”;
float Fees = 500.00;
75 JSON
▹A number (integer or
floating point)
▹A string (in double
quotes)
▹A Boolean (true or
false)
75
{
“Burger Price“ : 20.0
}
{
“Burger Name“ : “TK2323 Burger”
}
{
“Delicious“ : false
}
76 JSON
▹An array (in square brackets) ▹An object (in curly braces)
76
{
“Courses” : [ “TK2323”, “TR2312”,
“TP4345”]
}
“Student”: {
"name":“Ali",
"age":30,
“Matrix No":”A111111”
}
77 JSON: Nested
▹List of objects inside an array
▹A “books” object contains array of “language”, “edition”
and “lastName” object
77
78 JSON
Firebase Realtime
Database
Store and sync data in real time across all connected clients
79
Firebase – Instantiate80
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
// Initialize Firebase Auth and Database Reference
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mUserId = mFirebaseUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference();
Firebase – Ways to Save Data81
Set Write or replace data to a defined path,
like messages/users/<username>
update Update some of the keys for a defined path without replacing all
of the data
push
(append)
Add to a list of data in the database. Every time you push a new
node onto a list, your database generates a unique key,
like messages/users/<unique-user-id>/<username>
transaction Use our transactions feature when working with complex data
that could be corrupted by concurrent updates
Firebase – Add Data82
btt_add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Task task = new Task(et_new_task.getText().toString());
mDatabase.child("users").child(mUserId).child("tasks").push().setValue(task);
Intent intent = new Intent(AddTask.this, MainActivity.class);
startActivity(intent);
}
});
Firebase – Add Data83
Firebase – Read84
final Button btt_read = (Button) findViewById(R.id.add_task_btt_read);
btt_read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.addValueEventListener(new ValueEventListener() {
//This method will be called with a snapshot of the data at this location.
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String temp = String.valueOf(dataSnapshot.child("users").child(mUserId)
.child("tasks").getChildrenCount());
Toast.makeText(AddTask.this,“Count: "+temp,Toast.LENGTH_SHORT).show();
for (DataSnapshot postSnapshot: dataSnapshot.child("users").child(mUserId)
.child("tasks").child("-KW7tEHNtDfuc5NEOkvk").getChildren()) {
Toast.makeText(AddTask.this,“Data:"+ postSnapshot.toString(),Toast.LENGTH_LONG).show();
}
}@Override
.
.
.
Firebase – Read85
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MainActivity.this, "item:" + listView.getItemAtPosition(position),
Toast.LENGTH_LONG).show();
mDatabase.child("users").child(mUserId).child("tasks") //Select from users -> tasks
.orderByChild("title") //Where title =
.equalTo((String) listView.getItemAtPosition(position)) //"return the string"
.addListenerForSingleValueEvent(new ValueEventListener() { //Add a listener for a single change in
the data at this location. This listener will be triggered once with the value of the data at the location.
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
// Data is ordered by increasing height, so we want the first entry
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef().removeValue(); //Set the value at this location to 'null'
Toast.makeText(MainActivity.this, "Task Removed", Toast.LENGTH_SHORT).show();
}
}
8686
▹SQL queries equivalent in
Firebase
Firebase Realtime Database
87
Firebase –
Read
87
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
88 Firebase – Read
Select a user by UID
SELECT * FROM Users WHERE UID = 1;
const rootRef = firebase.database.ref();
const dataRef = rootRef.child(‘users’).child(‘1);
88
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
89 Firebase – Read
Select a user by email address
SELECT * FROM Users WHERE Email = ‘alice@email.com’;
const dataRef =
rootRef.child(‘users’).orderByChild(‘email’).equalTo(‘alice@email.com’);
89
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
90 Firebase – Read
Limit to 10 Users
SELECT * FROM Users LIMIT 10;
const dataRef = rootRef.child(‘users’).limitToFirst(10);
90
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
91 Firebase – Read
Get all users names that start with ‘D’
SELECT * FROM Users WHERE Name Like ‘D%’;
const dataRef =
rootRef.child(‘users’).orderByChild(‘name’).startAt(‘D’).endAt(‘Duf8ff’);
91
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
10 “Ravi” “ravi@email.com” 35 Kuala Lumpur
92 Firebase – Read
Get all users who are less than age 50
SELECT * FROM Users WHERE Age < 50;
const dataRef = rootRef.child(‘users’).orderByChild(‘age’).endAt(49);
92
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
93 Firebase – Read
Get all users who are greater than age 50
SELECT * FROM Users WHERE Age > 50;
const dataRef = rootRef.child(‘users’).orderByChild(‘age’).startAt(51);
93
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
94 Firebase – Read
Get all users who are between 20 and 100
SELECT * FROM Users WHERE Age >= 20 & Age <= 100 ;
const dataRef =
rootRef.child(‘users’).orderByChild(‘age’).startAt(20).endAt(100);
94
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
95 Firebase – Read
Get all users who are 28 and live in Berlin
SELECT * FROM Users WHERE Age = 28 AND Location = ‘Berlin’;
const dataRef =
rootRef.child(‘users’).orderByChild(‘age_location’).equalTo(’28_Berlin’);
95
UID (PK) Name Email Age Location
1 “David” “davi@email.com 99 SF
9 “Alice” “alice@email.com 28 Berlin
96
▹Example
DataSnapshot
Firebase – Update/Replace
Data97
btt_update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Task task = new Task(et_new_task.getText().toString());
mDatabase.child("users").child(mUserId)
.child("tasks").orderByChild("title") //Where title =
.equalTo(et_old_task.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef().setValue(task); //Set the value at this location to 'null'
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
DataSnapshot
▹ A DataSnapshot instance contains data from a
Firebase Database location.
▹ Any time you read Database data, you receive the
data as a DataSnapshot.
98
DataSnapshot
▹ DataSnapshots are passed to the methods in
listeners that you attach with
▹ addValueEventListener(ValueEventListener),
▹ addChildEventListener(ChildEventListener), or
▹ addListenerForSingleValueEvent(ValueEventListene
r).
99
Event Listener
▹ addValueEventListener(ValueEventListener)
▹ Read the data from the specific location
▹ addChildEventListener(ChildEventListener),
▹ Read the data from the child location
▹ addListenerForSingleValueEvent(ValueEventListene
r).
▹ Read only once
100
Firebase – Read101
final Button btt_read = (Button) findViewById(R.id.add_task_btt_read);
btt_read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.addValueEventListener(new ValueEventListener() {
//This method will be called with a snapshot of the data at this location.
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String temp = String.valueOf(dataSnapshot.child("users").child(mUserId)
.child("tasks").getChildrenCount());
Toast.makeText(AddTask.this,“Count: "+temp,Toast.LENGTH_SHORT).show();
for (DataSnapshot postSnapshot: dataSnapshot.child("users").child(mUserId)
.child("tasks").child("-KW7tEHNtDfuc5NEOkvk").getChildren()) {
Toast.makeText(AddTask.this,“Data:"+ postSnapshot.toString(),Toast.LENGTH_LONG).show();
}
}@Override
.
.
.
Firebase – Read102
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MainActivity.this, "item:" + listView.getItemAtPosition(position),
Toast.LENGTH_LONG).show();
mDatabase.child("users").child(mUserId).child("tasks") //Select from users -> tasks
.orderByChild("title") //Where title =
.equalTo((String) listView.getItemAtPosition(position)) //"return the string"
.addListenerForSingleValueEvent(new ValueEventListener() { //Add a listener for a single change in
the data at this location. This listener will be triggered once with the value of the data at the location.
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
// Data is ordered by increasing height, so we want the first entry
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef().removeValue(); //Set the value at this location to 'null'
Toast.makeText(MainActivity.this, "Task Removed", Toast.LENGTH_SHORT).show();
}
}
Firebase – Add Data103
btt_add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String id = databaseClubs.push().getKey();
// creat the club object
Club newClub = new Club(id,code,name);
// save the club information into the firebase
databaseClubs.child(id).setValue(newClub);
}
});
Firebase – Add Data104

Weitere ähnliche Inhalte

Was ist angesagt?

Firebase Introduction
Firebase Introduction Firebase Introduction
Firebase Introduction 9xdot
 
Introduction to Firebase with Android and Beyond...
Introduction to Firebase with Android and Beyond...Introduction to Firebase with Android and Beyond...
Introduction to Firebase with Android and Beyond...Kasper Loevborg Jensen
 
Mobile game architecture on GCP
Mobile game architecture on GCPMobile game architecture on GCP
Mobile game architecture on GCP명근 최
 
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...Amazon Web Services
 
Azure App Service
Azure App ServiceAzure App Service
Azure App ServiceBizTalk360
 
Introducing firebase
Introducing firebaseIntroducing firebase
Introducing firebaseFarouk Touzi
 
Firebase Cloud Messaging
Firebase Cloud MessagingFirebase Cloud Messaging
Firebase Cloud MessagingMohd Shamweel
 
Microsoft Azure Cloud Services
Microsoft Azure Cloud ServicesMicrosoft Azure Cloud Services
Microsoft Azure Cloud ServicesDavid J Rosenthal
 
Using Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidUsing Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidMagda Miu
 
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Tin Linn Soe
 
Gain Deep Visibility into APIs and Integrations with Anypoint Monitoring
Gain Deep Visibility into APIs and Integrations with Anypoint MonitoringGain Deep Visibility into APIs and Integrations with Anypoint Monitoring
Gain Deep Visibility into APIs and Integrations with Anypoint MonitoringInfluxData
 
Five Connectivity and Security Use Cases for Azure VNets
Five Connectivity and Security Use Cases for Azure VNetsFive Connectivity and Security Use Cases for Azure VNets
Five Connectivity and Security Use Cases for Azure VNetsKhash Nakhostin
 
What is new in Firebase?
What is new in Firebase?What is new in Firebase?
What is new in Firebase?Sinan Yılmaz
 
AWS 101: Introduction to AWS
AWS 101: Introduction to AWSAWS 101: Introduction to AWS
AWS 101: Introduction to AWSIan Massingham
 

Was ist angesagt? (20)

Firebase PPT
Firebase PPTFirebase PPT
Firebase PPT
 
Firebase Introduction
Firebase Introduction Firebase Introduction
Firebase Introduction
 
Azure web apps
Azure web appsAzure web apps
Azure web apps
 
Introduction to Firebase with Android and Beyond...
Introduction to Firebase with Android and Beyond...Introduction to Firebase with Android and Beyond...
Introduction to Firebase with Android and Beyond...
 
Mobile game architecture on GCP
Mobile game architecture on GCPMobile game architecture on GCP
Mobile game architecture on GCP
 
Firebase
FirebaseFirebase
Firebase
 
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...
Amazon Virtual Private Cloud (VPC): Networking Fundamentals and Connectivity ...
 
Azure App Service
Azure App ServiceAzure App Service
Azure App Service
 
Introducing firebase
Introducing firebaseIntroducing firebase
Introducing firebase
 
Firebase Cloud Messaging
Firebase Cloud MessagingFirebase Cloud Messaging
Firebase Cloud Messaging
 
Microsoft Azure Cloud Services
Microsoft Azure Cloud ServicesMicrosoft Azure Cloud Services
Microsoft Azure Cloud Services
 
Using Java to interact with Firebase in Android
Using Java to interact with Firebase in AndroidUsing Java to interact with Firebase in Android
Using Java to interact with Firebase in Android
 
Azure DevOps
Azure DevOpsAzure DevOps
Azure DevOps
 
Why Microservice
Why Microservice Why Microservice
Why Microservice
 
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
Microservices Platform with Spring Boot, Spring Cloud Config, Spring Cloud Ne...
 
Gain Deep Visibility into APIs and Integrations with Anypoint Monitoring
Gain Deep Visibility into APIs and Integrations with Anypoint MonitoringGain Deep Visibility into APIs and Integrations with Anypoint Monitoring
Gain Deep Visibility into APIs and Integrations with Anypoint Monitoring
 
Five Connectivity and Security Use Cases for Azure VNets
Five Connectivity and Security Use Cases for Azure VNetsFive Connectivity and Security Use Cases for Azure VNets
Five Connectivity and Security Use Cases for Azure VNets
 
What is new in Firebase?
What is new in Firebase?What is new in Firebase?
What is new in Firebase?
 
Serverless Architectures.pdf
Serverless Architectures.pdfServerless Architectures.pdf
Serverless Architectures.pdf
 
AWS 101: Introduction to AWS
AWS 101: Introduction to AWSAWS 101: Introduction to AWS
AWS 101: Introduction to AWS
 

Ähnlich wie Tk2323 lecture 8 firebase

Firebase integration with Flutter
Firebase integration with FlutterFirebase integration with Flutter
Firebase integration with Flutterpmgdscunsri
 
Mobile Programming - 10 Firebase
Mobile Programming - 10 FirebaseMobile Programming - 10 Firebase
Mobile Programming - 10 FirebaseAndiNurkholis1
 
Google Firebase Presentation
Google Firebase PresentationGoogle Firebase Presentation
Google Firebase PresentationAeni Patel
 
Firebase in a Nutshell
Firebase in a NutshellFirebase in a Nutshell
Firebase in a NutshellSumit Sahoo
 
Deploy Firebase Backend as a Service Model for Application Development
Deploy Firebase Backend as a Service Model for Application DevelopmentDeploy Firebase Backend as a Service Model for Application Development
Deploy Firebase Backend as a Service Model for Application DevelopmentDashTechnologiesInc
 
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdf
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdfAWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdf
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdfLaura Miller
 
intrduction to firebase.pptx
intrduction to firebase.pptxintrduction to firebase.pptx
intrduction to firebase.pptx21IT324MariAppan
 
Discover Google Firebase Platform
Discover Google Firebase PlatformDiscover Google Firebase Platform
Discover Google Firebase PlatformSagar Mody
 
Ibm bluemix
Ibm bluemix Ibm bluemix
Ibm bluemix Narendra
 
Top 5 Benefits Of Firebase Database System.pptx
Top 5 Benefits Of Firebase Database System.pptxTop 5 Benefits Of Firebase Database System.pptx
Top 5 Benefits Of Firebase Database System.pptxFlutter Agency
 

Ähnlich wie Tk2323 lecture 8 firebase (20)

Advance Mobile Application Development class 04
Advance Mobile Application Development class 04Advance Mobile Application Development class 04
Advance Mobile Application Development class 04
 
Firebase integration with Flutter
Firebase integration with FlutterFirebase integration with Flutter
Firebase integration with Flutter
 
Firebase Tech Talk By Atlogys
Firebase Tech Talk By AtlogysFirebase Tech Talk By Atlogys
Firebase Tech Talk By Atlogys
 
Mobile Programming - 10 Firebase
Mobile Programming - 10 FirebaseMobile Programming - 10 Firebase
Mobile Programming - 10 Firebase
 
Firebase Services
Firebase ServicesFirebase Services
Firebase Services
 
Firebase Android
Firebase AndroidFirebase Android
Firebase Android
 
Google Firebase Presentation
Google Firebase PresentationGoogle Firebase Presentation
Google Firebase Presentation
 
Firebase in a Nutshell
Firebase in a NutshellFirebase in a Nutshell
Firebase in a Nutshell
 
Deploy Firebase Backend as a Service Model for Application Development
Deploy Firebase Backend as a Service Model for Application DevelopmentDeploy Firebase Backend as a Service Model for Application Development
Deploy Firebase Backend as a Service Model for Application Development
 
Firebase
FirebaseFirebase
Firebase
 
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdf
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdfAWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdf
AWS Amplify vs. Firebase Selecting the Best Backend for Your Apps.pdf
 
19-03-22.pdf
19-03-22.pdf19-03-22.pdf
19-03-22.pdf
 
intrduction to firebase.pptx
intrduction to firebase.pptxintrduction to firebase.pptx
intrduction to firebase.pptx
 
Discover Google Firebase Platform
Discover Google Firebase PlatformDiscover Google Firebase Platform
Discover Google Firebase Platform
 
Google MLkit
Google MLkitGoogle MLkit
Google MLkit
 
Firebase
FirebaseFirebase
Firebase
 
Ibm bluemix
Ibm bluemix Ibm bluemix
Ibm bluemix
 
Top 5 Benefits Of Firebase Database System.pptx
Top 5 Benefits Of Firebase Database System.pptxTop 5 Benefits Of Firebase Database System.pptx
Top 5 Benefits Of Firebase Database System.pptx
 
Google Firebase
Google FirebaseGoogle Firebase
Google Firebase
 
Firebase & QA
Firebase & QAFirebase & QA
Firebase & QA
 

Mehr von MengChun Lam

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensorMengChun Lam
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api jsonMengChun Lam
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and threadMengChun Lam
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui uxMengChun Lam
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storageMengChun Lam
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler viewMengChun Lam
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql MengChun Lam
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intentMengChun Lam
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 uiMengChun Lam
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile applicationMengChun Lam
 

Mehr von MengChun Lam (11)

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intent
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
 

Tk2323 lecture 8 firebase

  • 1. Google Firebase TK2323 Mobile Programming Sem 1 2017/2018 Lam Meng Chun lammc@ukm.edu.my (G-02)
  • 3. Firebase Realtime Database Store and sync data in real time across all connected clients 3
  • 4. Firebase Realtime Database ▹ The Firebase Realtime Database is a cloud-hosted database. ▹ Data is stored as JSON and synchronized in realtime to every connected client. ▹ When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data. 4
  • 5. Firebase Realtime Database- KEY CAPABILITIES Realtime Instead of typical HTTP requests, the Firebase Realtime Database uses data synchronization—every time data changes, any connected device receives that update within milliseconds. Provide collaborative and immersive experiences without thinking about networking code. Offline Firebase apps remain responsive even when offline because the Firebase Realtime Database SDK persists your data to disk. Once connectivity is reestablished, the client device receives any changes it missed, synchronizing it with the current server state. 5
  • 6. Firebase Realtime Database- KEY CAPABILITIES Accessible from Client Devices The Firebase Realtime Database can be accessed directly from a mobile device or web browser; there’s no need for an application server. Security and data validation are available through the Firebase Realtime Database Security Rules, expression-based rules that are executed when data is read or written. 6
  • 8. Firebase Authentication Authenticate and manage users from a variety of providers without server-side code 8
  • 9. Firebase Authentication ▹ Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. ▹ It supports authentication using passwords, popular federated identity providers like Google, Facebook and Twitter, and more. 9
  • 10. Firebase Authentication - KEY CAPABILITIES FirebaseUI (beta) The FirebaseUI Auth component implements best practices for authentication on mobile devices and websites, which can maximize sign-in and sign-up conversion for your app. It also handles edge cases like account recovery and account linking that can be security sensitive and error-prone to handle correctly Email and password based authentication Authenticate users with their email addresses and passwords. The Firebase Authentication SDK provides methods to create and manage users that use their email addresses and passwords to sign in. Firebase Authentication also handles sending password reset emails. 10
  • 11. Firebase Authentication - KEY CAPABILITIES Federated identity provider integration Authenticate users by integrating with federated identity providers. The Firebase Authentication SDK provides methods that allow users to sign in with their Google, Facebook, Twitter, and GitHub accounts. Custom auth system integration Connect your app's existing sign-in system to the Firebase Authentication SDK and gain access to Firebase Realtime Database and other Firebase services. 11
  • 12. Firebase Authentication - KEY CAPABILITIES Anonymous auth Use Firebase features that require authentication without requiring users to sign in first by creating temporary anonymous accounts. If the user later chooses to sign up, you can upgrade the anonymous account to a regular account, so the user can continue where they left off. 12
  • 14. Firebase Cloud Messaging Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. 14
  • 15. Firebase Cloud Messaging ▹ Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user reengagement and retention. ▹ For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app. 15
  • 16. Firebase Cloud Messaging - KEY CAPABILITIES Send notification messages or data messages Send notification messages that are displayed to your user. Or send data messages and determine completely what happens in your application code. Versatile message targeting Distribute messages to your client app in any of three ways — to single devices, to groups of devices, or to devices subscribed to topics. 16
  • 17. Firebase Cloud Messaging - KEY CAPABILITIES Send messages from client apps Send acknowledgments, chats, and other messages from devices back to your server over FCM’s reliable and battery-efficient connection channel.. 17
  • 18. Firebase Notifications Firebase Notifications is a free service that enables targeted user notifications for mobile app developers. 18
  • 19. Firebase Notifications ▹ Built on Firebase Cloud Messaging and the FCM SDK, Firebase Notifications (Notifications) provides an option for developers and organizations seeking a flexible notification platform that requires minimal coding effort to get started, and a graphical console for sending messages. ▹ Using the Notifications console GUI, you can reengage and retain your userbase, foster app growth, and support marketing campaigns. 19
  • 20. Firebase Notifications- KEY CAPABILITIES Notifications analytics Analyze reengagement conversion with built-in notifications analytics collection and funnel analysis. Versatile message targeting Target clients in predefined user segments, custom analytics audiences, clients subscribed to topics, and single devices. 20
  • 21. Firebase Notifications- KEY CAPABILITIES Flexible message scheduling Deliver notifications (up to 2kb) immediately, or at a future time in the client's local time 21
  • 22. Firebase Storage Store and retrieve user-generated content such as images, audio and video without server-side code 22
  • 23. Firebase Storage ▹ Firebase Storage adds Google security to file uploads and downloads for your Firebase apps, regardless of network quality. ▹ You can use it to store images, audio, video, or other user-generated content. ▹ Firebase Storage is backed by Google Cloud Storage, a powerful, simple, and cost-effective object storage service. 23
  • 24. Firebase Storage - KEY CAPABILITIES Robust operations Firebase Storage performs uploads and downloads regardless of network quality. Uploads and downloads are robust, meaning they restart where they stopped, saving your users time and bandwidth. Strong security Firebase Storage integrates with Firebase Authentication to provide simple and intuitive authentication for developers. You can use our declarative security model to allow access based on filename, size, content type, and other High scalability Firebase Storage is backed by Google Cloud Storage for petabyte scale when your app goes viral. Effortlessly grow from prototype to production using the same infrastructure that powers Snapchat. 24
  • 25. Firebase Hosting Deploy web and mobile web apps in seconds using a secure global content delivery network 25
  • 26. Firebase Hosting ▹ Firebase Hosting is production-grade web content hosting for developers. ▹ With Hosting, you can quickly and easily deploy web apps and static content to a global content- delivery network (CDN) with a single command. 26
  • 27. KEY CAPABILITIES Served over a secure connection The modern web is secure. Zero- configuration SSL is built into Firebase Hosting so content is always delivered securely. Fast content delivery Each file you upload is cached on SSDs at CDN edges around the world. No matter where your users are, the content is delivered fast. 27
  • 28. KEY CAPABILITIES Rapid deployment Using the Firebase CLI, you can get your app up and running in seconds. Command line tools make it easy to add deployment targets into your build process. One-click rollbacks Quick deployments are great, but being able to undo mistakes is even better. Firebase Hosting provides full versioning and release management with one-click rollbacks. 28
  • 29. Firebase Test Lab for Android Test your Android apps against a wide range of physical devices 29
  • 30. Firebase Test Lab ▹ Firebase Test Lab for Android provides cloud-based infrastructure for testing Android apps. ▹ With one operation, you can initiate testing of your app across a wide variety of devices and device configurations. 30
  • 31. Firebase Test Lab ▹ Test results—including logs, videos, and screenshots—are made available in your project in the Firebase console. ▹ Even if you haven't written any test code for your app, Test Lab can exercise your app automatically, looking for crashes. 31
  • 32. Firebase Test Lab - KEY CAPABILITIES Test on real devices Use Test Lab to exercise your app on devices installed and running in a Google data center. Test Lab helps you to find issues that only occur on specific device configurations (for example, a Nexus 5 running a specific Android API level and specific locale settings). Run app tests, even if you haven't written any You can use Robo test to find issues with your app so you can test your app even if you haven't written app tests. Robo test analyzes the structure of your app's user interface and then explores it, automatically simulating user activities. If you have written instrumentation tests for your app, Test Lab can also run those tests. 32
  • 33. Firebase Test Lab - KEY CAPABILITIES Workflow integration Test Lab is integrated with Android Studio, the Firebase console, and the gcloud command line. You can also use Test Lab with Continuous Integration (CI) systems. 33
  • 34. Firebase Crash Reporting Get actionable insights and comprehensive analytics whenever your app crashes or stops working. 34
  • 35. Firebase Crash Reporting ▹Crash Reporting creates detailed reports of the errors in your app. ▹Errors are grouped into clusters of similar stack traces and triaged by the severity of impact on your users. ▹In addition to automatic reports, you can log custom events to help capture the steps leading up to a crash. 35
  • 36. Firebase Crash Reporting- KEY CAPABILITIES Monitor fatal and non-fatal errors Monitor fatal errors in iOS and fatal and non-fatal errors in Android. Reports are triaged by the severity of impact on users. Collect the data you need to diagnose problems Each report contains a full stack trace as well as device characteristics, performance data, and user circumstances when the error took place. Similar reports are automatically clustered to make it easier to identify related bugs. 36
  • 37. Firebase Crash Reporting- KEY CAPABILITIES Integrate with Analytics Errors captured are set as app_exception events in Analytics, allowing you to filter audiences based on who sees errors. Free and easy Crash Reporting is free to use. Once you've added Firebase to your app, it's just a few lines of code to enable comprehensive error reporting. 37
  • 39. Firebase Analytics Get detailed analytics to measure and analyse how users engage with your app 39
  • 40. FIREBASE ANALYTICS ▹a free and unlimited analytics tool built from the ground up for mobile apps. ▹Firebase Analytics is at the core of the Firebase platform, providing the insights you need to build successful apps. ▹Firebase Analytics helps you understand how your users behave, so you can make informed decisions about how to market your app. 40
  • 41. FIREBASE ANALYTICS - METRICS ▹average revenue per user (ARPU), ▹active users, ▹retention reports, ▹event counts ▹combined with user properties like device type, app version, and OS version to give you insight into how users interact with your app. 41
  • 42. KEY CAPABILITIES BigQuery Link your Firebase Analytics app to BigQuery where you can perform custom analysis on your entire Analytics dataset and import other data sources. Firebase Crash Reporting Firebase Analytics logs events for each crash so you can get a sense of the rate of crashes for different versions or regions, allowing you to gain insight into which users are impacted. You can also create audiences for users who have experienced multiple crashes and respond with Firebase Notifications directed at that audience. 42
  • 43. KEY CAPABILITIES Firebase Remote Config Use Firebase Analytics audience definitions to change the behavior and appearance of your app for different audiences without distributing multiple versions of your app. Google Tag Manager Integrating Google Tag Manager alongside Firebase Analytics enables you to manage your Firebase Analytics implementation remotely from a web interface after your app has been distributed. Firebase Notifications Firebase Analytics automatically logs events that correspond to your Firebase Notifications and supports reporting on the impact of each campaign. 43
  • 44. Firebase Remote Config Customise and experiment with app behaviour using server-side configuration parameters 44
  • 45. Firebase Remote Config ▹Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. ▹When using Remote Config, you create in-app default values that control the behavior and appearance of your app. ▹Then, you can later use the Firebase console to override in- app default values for all app users or for segments of your userbase. ▹Your app controls when updates are applied, and it can frequently check for updates and apply them with a negligible impact on performance. 45
  • 46. Firebase Remote Config - KEY CAPABILITIES Quickly roll out changes to your app's userbase You can make changes to your app's default behavior and appearance by changing server-side parameter values. For example, you could change your app's layout or color theme to support a seasonal promotion, with no need to publish an app update. Customize your app for segments of your userbase You can use Remote Config to provide variations on your app's user experience to different segments of your userbase by app version, by Firebase Analytics audience, by language, and more. 46
  • 47. Firebase Remote Config - KEY CAPABILITIES Run A/B tests to improve your app You can use Remote Config random percentile targeting with Firebase Analytics to A/B test improvements to your app across different segments of your userbase so that you can validate improvements before rolling them out to your entire userbase. 47
  • 49. Firebase App Indexing Firebase App Indexing gets your app into Google Search 49
  • 50. Firebase Remote Config ▹Firebase App Indexing gets your app into Google Search. If your Android app is already installed when users search for related content, they will launch your app directly from Search results. ▹If users don’t have your app yet, an install card shows up in Search results for Android. ▹Adding App Indexing promotes both types of app results within Google Search and also provides query autocompletions. 50
  • 52. AdMob Earn more from your apps the smart way by showing ads from millions of Google advertisers 52
  • 53. AdMob ▹AdMob by Google is a mobile advertising platform that you can use to generate revenue from your app. ▹Using AdMob with Firebase Analytics provides you with additional app usage data and analytics capabilities. ▹Firebase integrates with AdMob without requiring changes to your existing AdMob configuration. 53
  • 54. AdMob - KEY CAPABILITIES Earn more from AdMob's in-app ads Show ads from millions of Google advertisers in real time, or use AdMob Mediation to earn from over 40 premium networks through the AdMob platform to simplify your ad operations, improve competition, and earn more, for free. Improve user experience Native and video ads create a positive user experience as you monetize by matching the look and feel of your app. Choose from different ad templates, customize them, and experiment with different layouts on the fly without republishing your app. 54
  • 55. AdMob - KEY CAPABILITIES Scale fast ▹When your app's a global or domestic hit, you can monetize users quickly with AdMob, by showing ads to users in more than 200 markets. ▹More than one app? AdMob house ads is a free tool that enables you to cross-promote your apps to your userbase, across your family of apps. Access monetization reports AdMob is the premier monetization platform for mobile. While generating ad revenue, AdMob also produces its own monetization reports that you can use to make smarter decisions about product strategy. 55
  • 59. 59 59
  • 60. 60 60
  • 61. Firebase Authentication Authenticate and manage users from a variety of providers without server-side code 61
  • 62. Firebase – Instantiate62 private FirebaseAuth mFirebaseAuth; private FirebaseUser mFirebaseUser; private DatabaseReference mDatabase; // Initialize Firebase Auth and Database Reference mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseUser = mFirebaseAuth.getCurrentUser(); mUserId = mFirebaseUser.getUid(); mDatabase = FirebaseDatabase.getInstance().getReference();
  • 63. Firebase Authentication63 // initialize the FirebaseAuth instance mFirebaseAuth = FirebaseAuth.getInstance(); //If a user has signed in successfully you can get their account data at any point with the getCurrentUser method. //get a FirebaseUser object, which contains information about the signed-in user. mFirebaseUser = mFirebaseAuth.getCurrentUser(); if (mFirebaseUser == null) { // Not logged in, launch the Log In activity loadLogInView(); } else { // User is signed in mUserId = mFirebaseUser.getUid(); }
  • 64. Firebase Authentication - signup64 mFirebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Intent intent = new Intent(SignUpActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else { AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this); builder.setMessage(task.getException().getMessage()) .setTitle(R.string.login_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } });
  • 65. Firebase Authentication - signin65 mFirebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(LogInActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { GoToMainAvtivity(); } else { Toast.makeText(LogInActivity.this,"Error",Toast.LENGTH_SHORT).show(); } } });
  • 66. Firebase Authentication - SignOut66 @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_logout) { mFirebaseAuth.signOut(); Intent intent = new Intent(MainActivity.this, LogInActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); }
  • 67. Firebase Authentication – Check User Status67 if (mFirebaseUser == null) { // go to loginpage Intent intent = new Intent(MainActivity.this, LogInActivity.class); startActivity(intent); }
  • 71. 71 JSON ▹JSON (JavaScript Object Notation) is a lightweight data- interchange format. ▸Data is in name/value pairs ▸Data is separated by commas , ▸Curly braces hold objects { } ▸Square brackets hold arrays [ ] 71
  • 72. 72 Name/Value pairs Name Value: { “Matrix No” : “A111111” }
  • 73. 73 JSON ▹JSON values can be: ▸A number (integer or floating point) ▸A string (in double quotes) “” ▸A Boolean (true or false) ▸An array (in square brackets) [] ▸An object (in curly braces) {} ▸null 73
  • 74. 74 Name/Value pairs Name Value: { “Matrix No” : “A111111” } { “Fees” : 500.00} String Matrix No = “A111111”; float Fees = 500.00;
  • 75. 75 JSON ▹A number (integer or floating point) ▹A string (in double quotes) ▹A Boolean (true or false) 75 { “Burger Price“ : 20.0 } { “Burger Name“ : “TK2323 Burger” } { “Delicious“ : false }
  • 76. 76 JSON ▹An array (in square brackets) ▹An object (in curly braces) 76 { “Courses” : [ “TK2323”, “TR2312”, “TP4345”] } “Student”: { "name":“Ali", "age":30, “Matrix No":”A111111” }
  • 77. 77 JSON: Nested ▹List of objects inside an array ▹A “books” object contains array of “language”, “edition” and “lastName” object 77
  • 79. Firebase Realtime Database Store and sync data in real time across all connected clients 79
  • 80. Firebase – Instantiate80 private FirebaseAuth mFirebaseAuth; private FirebaseUser mFirebaseUser; private DatabaseReference mDatabase; // Initialize Firebase Auth and Database Reference mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseUser = mFirebaseAuth.getCurrentUser(); mUserId = mFirebaseUser.getUid(); mDatabase = FirebaseDatabase.getInstance().getReference();
  • 81. Firebase – Ways to Save Data81 Set Write or replace data to a defined path, like messages/users/<username> update Update some of the keys for a defined path without replacing all of the data push (append) Add to a list of data in the database. Every time you push a new node onto a list, your database generates a unique key, like messages/users/<unique-user-id>/<username> transaction Use our transactions feature when working with complex data that could be corrupted by concurrent updates
  • 82. Firebase – Add Data82 btt_add.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Task task = new Task(et_new_task.getText().toString()); mDatabase.child("users").child(mUserId).child("tasks").push().setValue(task); Intent intent = new Intent(AddTask.this, MainActivity.class); startActivity(intent); } });
  • 84. Firebase – Read84 final Button btt_read = (Button) findViewById(R.id.add_task_btt_read); btt_read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDatabase.addValueEventListener(new ValueEventListener() { //This method will be called with a snapshot of the data at this location. @Override public void onDataChange(DataSnapshot dataSnapshot) { String temp = String.valueOf(dataSnapshot.child("users").child(mUserId) .child("tasks").getChildrenCount()); Toast.makeText(AddTask.this,“Count: "+temp,Toast.LENGTH_SHORT).show(); for (DataSnapshot postSnapshot: dataSnapshot.child("users").child(mUserId) .child("tasks").child("-KW7tEHNtDfuc5NEOkvk").getChildren()) { Toast.makeText(AddTask.this,“Data:"+ postSnapshot.toString(),Toast.LENGTH_LONG).show(); } }@Override . . .
  • 85. Firebase – Read85 listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) { Toast.makeText(MainActivity.this, "item:" + listView.getItemAtPosition(position), Toast.LENGTH_LONG).show(); mDatabase.child("users").child(mUserId).child("tasks") //Select from users -> tasks .orderByChild("title") //Where title = .equalTo((String) listView.getItemAtPosition(position)) //"return the string" .addListenerForSingleValueEvent(new ValueEventListener() { //Add a listener for a single change in the data at this location. This listener will be triggered once with the value of the data at the location. @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChildren()) { // Data is ordered by increasing height, so we want the first entry DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next(); firstChild.getRef().removeValue(); //Set the value at this location to 'null' Toast.makeText(MainActivity.this, "Task Removed", Toast.LENGTH_SHORT).show(); } }
  • 86. 8686 ▹SQL queries equivalent in Firebase Firebase Realtime Database
  • 87. 87 Firebase – Read 87 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 88. 88 Firebase – Read Select a user by UID SELECT * FROM Users WHERE UID = 1; const rootRef = firebase.database.ref(); const dataRef = rootRef.child(‘users’).child(‘1); 88 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 89. 89 Firebase – Read Select a user by email address SELECT * FROM Users WHERE Email = ‘alice@email.com’; const dataRef = rootRef.child(‘users’).orderByChild(‘email’).equalTo(‘alice@email.com’); 89 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 90. 90 Firebase – Read Limit to 10 Users SELECT * FROM Users LIMIT 10; const dataRef = rootRef.child(‘users’).limitToFirst(10); 90 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 91. 91 Firebase – Read Get all users names that start with ‘D’ SELECT * FROM Users WHERE Name Like ‘D%’; const dataRef = rootRef.child(‘users’).orderByChild(‘name’).startAt(‘D’).endAt(‘Duf8ff’); 91 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin 10 “Ravi” “ravi@email.com” 35 Kuala Lumpur
  • 92. 92 Firebase – Read Get all users who are less than age 50 SELECT * FROM Users WHERE Age < 50; const dataRef = rootRef.child(‘users’).orderByChild(‘age’).endAt(49); 92 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 93. 93 Firebase – Read Get all users who are greater than age 50 SELECT * FROM Users WHERE Age > 50; const dataRef = rootRef.child(‘users’).orderByChild(‘age’).startAt(51); 93 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 94. 94 Firebase – Read Get all users who are between 20 and 100 SELECT * FROM Users WHERE Age >= 20 & Age <= 100 ; const dataRef = rootRef.child(‘users’).orderByChild(‘age’).startAt(20).endAt(100); 94 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 95. 95 Firebase – Read Get all users who are 28 and live in Berlin SELECT * FROM Users WHERE Age = 28 AND Location = ‘Berlin’; const dataRef = rootRef.child(‘users’).orderByChild(‘age_location’).equalTo(’28_Berlin’); 95 UID (PK) Name Email Age Location 1 “David” “davi@email.com 99 SF 9 “Alice” “alice@email.com 28 Berlin
  • 97. Firebase – Update/Replace Data97 btt_update.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final Task task = new Task(et_new_task.getText().toString()); mDatabase.child("users").child(mUserId) .child("tasks").orderByChild("title") //Where title = .equalTo(et_old_task.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChildren()) { DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next(); firstChild.getRef().setValue(task); //Set the value at this location to 'null' } } @Override public void onCancelled(DatabaseError databaseError) { } }); } });
  • 98. DataSnapshot ▹ A DataSnapshot instance contains data from a Firebase Database location. ▹ Any time you read Database data, you receive the data as a DataSnapshot. 98
  • 99. DataSnapshot ▹ DataSnapshots are passed to the methods in listeners that you attach with ▹ addValueEventListener(ValueEventListener), ▹ addChildEventListener(ChildEventListener), or ▹ addListenerForSingleValueEvent(ValueEventListene r). 99
  • 100. Event Listener ▹ addValueEventListener(ValueEventListener) ▹ Read the data from the specific location ▹ addChildEventListener(ChildEventListener), ▹ Read the data from the child location ▹ addListenerForSingleValueEvent(ValueEventListene r). ▹ Read only once 100
  • 101. Firebase – Read101 final Button btt_read = (Button) findViewById(R.id.add_task_btt_read); btt_read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDatabase.addValueEventListener(new ValueEventListener() { //This method will be called with a snapshot of the data at this location. @Override public void onDataChange(DataSnapshot dataSnapshot) { String temp = String.valueOf(dataSnapshot.child("users").child(mUserId) .child("tasks").getChildrenCount()); Toast.makeText(AddTask.this,“Count: "+temp,Toast.LENGTH_SHORT).show(); for (DataSnapshot postSnapshot: dataSnapshot.child("users").child(mUserId) .child("tasks").child("-KW7tEHNtDfuc5NEOkvk").getChildren()) { Toast.makeText(AddTask.this,“Data:"+ postSnapshot.toString(),Toast.LENGTH_LONG).show(); } }@Override . . .
  • 102. Firebase – Read102 listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) { Toast.makeText(MainActivity.this, "item:" + listView.getItemAtPosition(position), Toast.LENGTH_LONG).show(); mDatabase.child("users").child(mUserId).child("tasks") //Select from users -> tasks .orderByChild("title") //Where title = .equalTo((String) listView.getItemAtPosition(position)) //"return the string" .addListenerForSingleValueEvent(new ValueEventListener() { //Add a listener for a single change in the data at this location. This listener will be triggered once with the value of the data at the location. @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChildren()) { // Data is ordered by increasing height, so we want the first entry DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next(); firstChild.getRef().removeValue(); //Set the value at this location to 'null' Toast.makeText(MainActivity.this, "Task Removed", Toast.LENGTH_SHORT).show(); } }
  • 103. Firebase – Add Data103 btt_add.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String id = databaseClubs.push().getKey(); // creat the club object Club newClub = new Club(id,code,name); // save the club information into the firebase databaseClubs.child(id).setValue(newClub); } });
  • 104. Firebase – Add Data104