Exploring Firebase Authentication & Database
It would not be an exaggeration if we said that technological advancements are running at the speed of light or maybe even faster than that. As enthusiastic developers, we need to keep up with it. In other words, the best part about IT is that there's something new to learn every day.
Having used Firebase for multiple projects, I can tell you it's definitely worth talking about. Firebase, a mobile and web application platform with tools and infrastructure, has been designed as an aid to developers to support them in building apex quality applications. It is a complete set of harmonious features that can be mixed and matched depending on your needs.
Firebase at a Glance
Though Firebase offers several useful services, like AdMob, AdWord, Cloud Massaging, Crash Reporting, Notification, Remote Notifications, and Invites, I was mostly drwan to its core services such as Real time Database, Storage, Hosting, Test Lab, Authentication, and Analytics during my own experience working with top-notch apps.
I would like to talk briefly storage and hosting first. Backed by Google Cloud Storage, Firebase Storage is a secured and robust storage place to store and serve user generated contents. Despite issues in network quality, uploads, and downloads, it works tremendously well in saving time and bandwidth. Its extensibility is so high, it can even power Snapchat! Firebase Hosting offers quick and assured static hosting for web applications. When it comes to deploying web apps and static content to a global content-delivery network (CDN), it's extremely zippy — Firebase performs it with a single command. Apart of fast content delivery in any part of the world, its one-click rollbacks to undo mistakes and to handle release management make it almost unbeatable.
Modeling Frame for Chat Application – To understand Firebase
As a developer, you can make the most out of its pragmatic sides. In this blog, we will create a simple Chat Application using Firebase with the goal to explore Firebase Authentication and Firebase Database.
In this Chat Application, the demo user will be able to chat by using login details of their Google account. To start, first we need to create a Firebase Console Project and then we need to connect the Android App to Firebase Project.
Kindly go to the this link and follow the explanation step by step.
Make sure that you create a Firebase Console Project and connect your Android App to it.
After connecting the Android Project, we will explore the following features:
- Authentication
- Database
1. Authentication
Firebase Authentication is a drop-in authentication solution that can take care of the end-to-end User Interface flows on any mobile or computer device. It allows users to sign in with their email address and password as well as with Google Sign-In and Facebook Login. It's easy to customize the UI for your desired look and feel and it can also handle security sensitive matters with accounts recovery and account linking processes.
Most major apps need to know the user's identity. Firebase provides great support to authenticate your app's users. Now, we will use the Google provider as the sign in method for this demo app.
The following steps will demonstrate how your can authenticate Android apps using Google sign in provider.
Step 1: Go to your Firebase project console and click "Select Authentication." Now, we have to provide a sign in method for our application. So click on "SIGN IN METHOD" and enable Google sign in method and click "SAVE."
Step 2: Add the dependencies for Firebase Authentication and Google Sign In to your app level build.gradle
file.
compile ‘com.google.firebase:firebase-auth:10.0.1’
compile ‘com.google.android.gms:play-services-auth:10.0.1’
Step 3: Now, in your Android App, you will have to setup the Google Sign In option. Fir successful Google Sign In, you have to authenticate it with Firebase. You can authenticate your app to Firebase like so:
First you have to retrieve AutoCredential
object from GoogleSignInAccount
object, and then you can authenticate FirebaseAuth
Instance with the AutoCredential
object as shown in a code:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.d(TAG, "signInWithCredential", task.getException());
Toast.makeText(GoogleSignActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(GoogleSignActivity.this, "Authentication Sucessful.",Toast.LENGTH_SHORT).show();
}
}
});
}
You have successfully authenticated the Firebase!
Note: To sign out of a current user & clear disk cache, call signOut()
.
2. Database
Firebase Database has a unique fort that's made firebase as popular as BaaS. It stores and syncs data with NoSQL cloud database. Data storing as JSON and its real time synchronization for deriving automatic updates (with the newest data from each connected client, even when app goes offline) are the most sensible part of it.
For Firebase database specific user access, you have to change the security rules of your database depending on your requirements. By default, security rule for the database require user to be authenticated.
Note: To learn more about security rules refer this link.
Now, the following steps will demonstrate the Firebase database integration in our application.
Step 1: Add the dependency for Firebase real time database to your app level build.gradle
file.
compile ‘com.google.firebase:firebase-database:10.0.1’
Step 2: Create a DatabaseReference
of messages tag as below.
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference messageDatabaseReference = mFirebaseDatabase.getReference(TAG_MESSAGES);
As we are using Message Java object, which is shown below, the content of your object is automatically mapped to Firebase location in a nested fashion. If you're using the pojo class, you must define a default constructor for the said class.
public class Message
{
private String content;
private String sender;
private long timeStamp;
public Message()
{
// default constructor
}
public Message(String messageContain, String messageSender, long timeStamp)
{
this.content = messageContain;
this.sender = messageSender;
this.timeStamp = timeStamp;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
}
To upload the data, you can you can use the setValue()
method like so:
Message m = new Message(messageContent, mUserName, currentTimeInMillis);
String messageId = mDateDatabaseReference.push().getKey();
Message tMessage = new Message(messageContent, messageSender, timeStamp);
mDateDatabaseReference.child(messageId).setValue(tMessage);
Note: push()
is used to create a node in messages node at /messages/$messageid
.
This is how we can send the message to Firebase and this will instantly update its database and give notification to all its client related data addition.
Step 3: Now add ValueEventListener
to DatabaseReference
object so we can get the real time database changes from Firebase. It will update the adapter for every change that's received by ValueEventListener
.
mDatabaseReference.addValueEventListener(mValueEventListener);
// instance of valueEventListener
private ValueEventListener mValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//update the Recycler view adapter to display the changes in db
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
Toast.makeText(MainActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
}
};
Note: If we are using Android studio version 2.2 preview3 and above, then we can setup the Firebase project and build.gradle
from Android studio by clicking on Tools -> Firebase -> Select Authentication and Database. It will open browser and ask for Google login by signing in. It will create the project on Firebase console automatically and add dependencies in build.gradle
file.
Conclusion
Here, we have started a compact understanding of the coherent sides of Firebase platform. If you are about to develop a new business application or revamp existing configurations, Firebase is an available option for you. Firebase is at its best when handling apps that retain a centralized database, apps that are being updated by multiple users, and apps that must notify relevant updates to users. Firebase would save plenty of time so that coding experts can focus more on core functionalities that will lead their applications to greater success.
For a detailed explaination of how Firebase can be integrated to your Android app, read this article.
If you want to learn more about Firebase, feel free to contact me at www.azilen.com.
how to login with real time database in firebase
you can login using Authentication feature of Firebase.
Firebase sucks! Use Postgresql, (flies away)