Adding Firebase to Android app
Dmytro Zubov, PhD
[email protected]Naryn, Kyrgyzstan, 11:03am, Sept 29, 2022
Lessons learnt last time
• MQTT Messenger: Java Android app
• Types of variables in Java
• Types of modifiers in Java
• Java types
• Compound expressions in Java
• Bitwise operators in Java
What we gonna discuss today?
• What is Firebase?
• History of Firebase
• Why use Firebase?
• General architecture
• Services
• Adding Firebase Realtime Database to Android app
What is Firebase?
https://www.youtube.com/watch?v=vAoB4VbhRzM
• Firebase in 100 Seconds
What is Firebase?
• Firebase is a fully managed platform for building iOS,
Android, and web apps that provides automatic data
synchronization, authentication services, messaging, file
storage, analytics, and more. Starting with Firebase is an
efficient way to build or prototype mobile backend
services.
What is Firebase?
• A set of tools which provides a full suite for app
development
• NoSQL database
• Based on node.js
• Real-time syncing with multiple devices or chat
application
• Ability to create applications with no server-side
programming
• Backend-as-a-Service
What is Firebase?
https://www.youtube.com/watch?v=dRYnm_k3w1w&feature=emb_logo
• Getting started with Firebase on Android
History of Firebase
• Founded in 2011 by Andrew Lee and James Tamplin
• Initial product was a real-time database
• Over time it becomes a full suite for app development
• Acquired by Google in 2014
Why use Firebase?
• Create app without backend server
• No need extra money spent for backend server. Ok,
sometimes, we need :(
• Push notification
• NoSQL database so it is faster
• Auto backup
• and many more…
General architecture
• Firebase client is added to an application by including
the relevant Firebase library
• Firebase has libraries for JavaScript, Java, Android, iOS
and a REST API. More features - ?
• Once it is added any data structure can be saved to
Firebase
• This will automatically save data to Firebase backend
and synchronize the data across various instances of the
application
General architecture (cont.)
REST, or REpresentational State Transfer, is an
architectural style for providing standards between
computer systems on the web, making it easier for
systems to communicate with each other.
https://www.codecademy.com/articles/what-is-rest
Services
Services (cont.)
• Analytics
Unlimited reporting of 500 event types, each with up to 25
attributes
One dashboard to view user behavior and cross-network
campaign performance
Demographic segmentation, including age, gender, and
location, available out-of-the-box
Export raw data to BigQuery for custom querying
Services (cont.)
• Cloud messaging
Send unlimited upstream/downstream messages
Send messages to individual devices or a user segment
Handle all aspects of queuing and delivery
It can send billions of messages with 95% of messages sent in
250ms
Services (cont.)
• Authentication
Support multiple social accounts
Optional, out-of-the-box authentication UI optimized to give
your users the best experience
It can also integrate to your existing accounts
Advanced functionality like email verification, anonymous
accounts, and account linking
Firebase will also manage user session
Services (cont.)
• Realtime database
A cloud-hosted NoSQL database
Intuitive and easy-to-use API
Remains responsive regardless of network latency or Internet
connectivity
Handles the complexity of real time synchronization and
provides flexible conflict resolution
Accessible directly from client SDKs, or from the server with the
REST API
Services (cont.)
• Storage
Robust uploads and downloads in the background, regardless of
network quality
Secure client-side authorization, integrated with Authentication
Petabyte scale data storage backed by Google Cloud Storage
API access throughout Firebase or Google Cloud Storage APIs
Services (cont.)
• Hosting
Automatically provisioned SSL certificate
Support for client-side routing
Blazing-fast content worldwide
Atomic deploys and one-click rollbacks on one command
Every site is served over secured connection
Services (cont.)
• Test lab
Generate detailed reports and screenshots to help identify bugs
Run custom test scripts on hundreds of device configurations
Supplement your existing workflow through integration with
Android Studio, command-line tools, and Web-based consoles
Services (cont.)
• Crash reporting
Prioritize crashes by frequency and impact
Comprehensive data surrounding each crash, including device
characteristics, device circumstances, a stack trace, and more
Reliably collect crashes that occur while the device is online or
offline
Services (cont.)
• Notification
Send free and unlimited notifications across Android and iOS
Send messages and analyze effectiveness in one dashboard
without writing any code
Integrate with Firebase Analytics to deliver messages to a user
segment
Services (cont.)
• Remote config
Modify your app without a new production deployment
Customize content for different Firebase Analytics audiences
and measure results
Roll out features gradually and monitor the impact
Services (cont.)
• App indexing
Show your in-app content via Google Search
Make your content accessible through auto complete and Now
on Tap for Android device
Improve your app ranking in Google Search results
Services (cont.)
• Dynamics links
Improve acquisition and engagement by bringing users directly
to content that they were originally searching for, whether they
have your app installed or not
Delight new users with personalized promotions and messages
after install
Services (cont.)
• Invites
Invite the most relevant contacts with smart suggestions
Free email and SMS delivery
Powered by Firebase Dynamic Links
Services (cont.)
• AdWords
Conversion tracking for first opens and in-app events without
implementing any additional SDKs
Cross-network attribution measurement and LTV in one
dashboard
Show ads to users based on user segments from Firebase
Analytics
Services (cont.)
• AdMOB
Show ads from millions of Google advertisers competing in real
time
Choose a format to suit your app, including banner, video and
native ads
Work with more than 40 top ad networks using AdMob
Mediation
Cross-promote between your apps for free with AdMob house
ads
Adding Firebase Realtime Database to Android app
• About JSON structured data
The data stored in the Firebase Realtime Database is JSON structured,
i.e., the entire database will be a JSON tree with multiple nodes
Unlike SQL database, Firebase Realtime Database doesn't have tables
or records in the JSON tree. Whenever we are adding some data to the
JSON tree, then it becomes a node in the existing JSON structure with
some key associated with it. All Firebase Realtime Database data is
stored as JSON objects.
Following is an example of JSON structured data:
Adding Firebase Realtime Database to Android app
• Prerequisites
Install or update Android Studio to its latest version (ok, 4.0 is good enough)
Make sure that your project meets these requirements:
- Targets API level 16 (Jelly Bean) or later Oct 3, 2022:
- Uses Gradle 4.1 or later Android Studio Dolphin 2021.3.1
- Uses Jetpack (AndroidX), which includes meeting these version
requirements:
com.android.tools.build:gradle v3.2.1 or later
compileSdkVersion 28 or later
Set up a physical device or use an emulator to run your app
Emulators must use an emulator image with Google Play
Sign into Firebase using your Google account
Adding Firebase Realtime Database to Android app
• Database configuration rules
The data present in the database is very important and we
shouldn't give access to everyone to use the data present in our
database. So, Firebase Realtime Database has some database
configuration rules that can be used to provide different access to
different users:
- Default
- Public
- User
https://blog.mindorks.com/firebase-realtime-database-android-tutorial
Adding Firebase Realtime Database to Android app
• Database configuration rules
Default: By default, the read and write access to our database is
disabled and no one can read or write data from the database in
this mode. Here, we can access the data of the database from the
Firebase Console only.
Adding Firebase Realtime Database to Android app
• Database configuration rules
Public: By using public rules, anyone can change the data
presented in the database. This rule is generally used when we
are testing our application and after testing the app, we can set
the rule to User only.
Adding Firebase Realtime Database to Android app
• Database configuration rules
User: In this rule, the user of our application can read and write
in our database. We can authenticate our user using the Firebase
Login and Authentication and after that, our user will have the
access to our database.
Firebase Realtime Database Creation in 5 mins
https://www.youtube.com/watch?v=qKxisFLQRpQ
Adding Firebase Realtime Database to Android app
• Create the Firebase Realtime database and connect it
to our Android project
Step 1. Open Android Studio and create a new project or open an
existing project.
Step 2. In Android Studio, log in with your Google account email.
You can find the login button at the top right corner of the
Android Studio. (Pls remember the email ID that you have used
here :)
Adding Firebase Realtime Database to Android app
• If we create a new empty Android project:
Adding Firebase Realtime Database to Android app
Step 3. Open the Firebase website and login into it (use the same
email id as used in Android Studio for login)
Step 4. After login, click on the "Go To Console" button that is
present of the upper right side of the website
Adding Firebase Realtime Database to Android app
Step 5. Click on "Add Project"
Adding Firebase Realtime Database to Android app
Step 6. Enter the required details of the project and click on
submit
Adding Firebase Realtime Database to Android app
Step 7. After creating a project, we will see the below image (or
something similar :) of our project dashboard
Adding Firebase Realtime Database to Android app
Step 8. Click on "Database" and then in the Realtime Database
section, click on "Create Database"
Adding Firebase Realtime Database to Android app
Step 9. We use the database for the educational purpose. Hence,
select the "Start in test mode" option and click on enable.
Adding Firebase Realtime Database to Android app
Step 10. Now, come back to our Android Studio project. We have
to connect our Firebase project with the Android Studio project.
So, click on Tools > Firebase > Realtime Database > Save and
retrieve data OR
“Get started with Realtime Database”
Adding Firebase Realtime Database to Android app
Step 11. After that click on "Connect to Firebase". A list of
projects will be shown to you. Select the project that you have
created on the Firebase website and click on "Connect to
Firebase".
Adding Firebase Realtime Database to Android app
Step 12. Lastly, we have to add the dependency of Firebase
Realtime Database in our project by clicking on "Add the Realtime
Database SDK to your app" button and then "Accept changes".
Adding Firebase Realtime Database to Android app
• To develop the app, we use Android Studio Dolphin 2021.3.1
Adding Firebase Realtime Database to Android app
• How to write a database
Here, getInstance() is used to get the complete instance of the
Database. Then, with the help of that instance, we store the data
at the particular location as shown in the below code:
public void WriteInfotoFirebase (View view){
// Write a message to the database
// Get the database instance and store into object
FirebaseDatabase database = FirebaseDatabase.getInstance();
// getReference() gets the reference if the reference is already created...
// if reference is not created then it will create a new reference here
DatabaseReference myRef = database.getReference("message");
// assign value to the particular reference
myRef.setValue("Hello, World! Time-date is "+
Calendar.getInstance().getTime());
}
https://firebasetutorials.com/create-firebase-realtime-database/
Adding Firebase Realtime Database to Android app
The Database reference looks like in the Firebase
console in the below image (the yellow color means
that the node was updated):
Adding Firebase Realtime Database to Android app
If we want to create a multi-node database, we can set the path
in the getReference() as follows (we can also use .child() to get
the same results):
public void WriteInfotoFirebaseMultiNode (View view){
// Write a message to the database
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
// Set path to get the multiple dropdown nodes
DatabaseReference myRef = database.getReference("message/java/user");
myRef.setValue("Hello, World! Time-date is "+ Calendar.getInstance().getTime());
//We can also use .child() to get the same results
myRef = database.getReference("message1").child("java").child("user");
myRef.setValue("Hello, World! Time-date is "+ Calendar.getInstance().getTime());
}
Adding Firebase Realtime Database to Android app
• How to read database
To update our app data in the real-time, we have to attach a
ValueEventListener to the object of the reference we have created above.
onDataChange() method is called once when this method is attached to the
listener, whenever a data is changed, including their children’s
onDataChange() method triggered again.
FirebaseDatabase database = FirebaseDatabase.getInstance();
// getReference() gets the reference if the reference is already created...
// if reference is not created then it will create a new reference here
DatabaseReference myRef = database.getReference("message");
private static final String TAG=MainActivity.class.getSimpleName();
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textViewID);
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated
try{
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "Value is: " + value);
textView.setText(value);
} catch (Exception exception){}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.i(TAG, "Failed to read value.", error.toException());
}
});
}
Adding Firebase Realtime Database to Android app
• How to delete node from database
We can delete the node by putting the reference path and
setting the value to null or by attaching removeValue() to it
public void DeleteNode (View view){
DatabaseReference dbNode =
FirebaseDatabase.getInstance().getReference().getRoot().child("message1").child("java").
child("user");
dbNode.setValue(null);
//or we can delete the node with the following code too
DatabaseReference dbNodetwo =
FirebaseDatabase.getInstance().getReference().getRoot()
.child("message");
dbNodetwo.removeValue();
}
Adding Firebase Realtime Database to Android app
When we delete the node, it will instantly update in the real-
time database. In the image below, we can see that when we
delete the node it will turn red and then remove from the real-
time database console
Adding Firebase Realtime Database to Android app
• How to update node in the database
.setValue(“String”); is used to set the value in the database
Also, we can attach the listener just to know whether the operation is
successful or not
public void UpdateNode (View view){
DatabaseReference reference = database.getReference().child("message");
reference.setValue("Hello, World! Time-date is "+ Calendar.getInstance().getTime())
// we can also attach listener just to know whether it is successful or not
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Write was successful!
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Write failed
}
});
}
Adding Firebase Realtime Database to Android app
• if we need to use Google Services, we have to add the
following lines of code inside the build.gradle (Project) file:
plugins {
id 'com.android.application' version '7.2.0' apply false
id 'com.android.library' version '7.2.0' apply false
id 'com.google.gms.google-services' version '4.3.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and be sure that we have the following plugin IDs inside the
build.gradle (Module) file:
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
Adding Firebase Realtime Database to Android app
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewID"
android:layout_width="350dp"
android:layout_height="133dp"
android:text="Let us play with Firebase"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.146" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:onClick="WriteInfotoFirebase"
android:text="Write info to Firebase"
• activity_main.xml is as follows:
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewID" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:onClick="WriteInfotoFirebaseMultiNode"
android:text="Write info: Multi-node"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:onClick="DeleteNode"
android:text="Delete node"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button2" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:onClick="UpdateNode"
android:text="Update node"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button3" />
</androidx.constraintlayout.widget.ConstraintLayout>
Adding Firebase Realtime Database to Android app
• An example with smartphone Pixel 4 (API 32, Android
12, Google Play):
Adding Firebase Realtime Database to Android app
• Perhaps we need to add the file google-services.json
manually: https://stackoverflow.com/questions/33866061/error-file-google-services-json-is-missing-from-module-root-folder-the-google/50173745
1. Goto https://console.firebase.google.com/
2. Select your project
3. On the left menu, click on settings > project settings
4. Add an app or download the google-services.json file under
the Your App section
Do you have any
questions or
comments?
Thank you
for your attention !
In this presentation:
• Some icons were downloaded from flaticon.com and iconscout.com