Building Real-time Android Chatroom With FirebaseMendhie EmmanuelBlockedUnblockFollowFollowingMar 20I particularly enjoy working with Firebase because of the ease it brings to the development process.
Firebase efficiently handles the backend process associated with authentication, cloud storage, real-time database, and push notification while you focus on developing the app.
In this article, I’ll show you how to build a realtime android chatroom with Firebase.
Trust me, it will be interesting and straight-to-point.
This article covers the following core areas:Creating Firebase projectSetting up Firebase authentication, cloud firestore, and storageUser authentication with email/passwordUsing FirebaseUI for Cloud FirestoreCRUD operation on Cloud FirestoreAlright guys, let’s begin.
Create your project and link to FirebaseSteps to add Firebase to android appCreate your project on Android Studio, then follow these steps to add Firebase to it.
Go to the Firebase console.
Click Add project, then enter your Project name.
Click Create project.
Now that you have created a Firebase project, add your app to it:Click Add Firebase to your Android app and follow the setup steps.
When prompted, enter your app’s package name.
Click Download google-services.
json to obtain your Firebase Android config file (google-services.
Move the config file into the same directory as your root-level build.
Add the initialization code, then run your app to send verification to the Firebase console that you’ve successfully installed Firebase.
Setup authentication, cloud firestore, and Firebase storageSetting up Firebase authentication, cloud firestore, and cloud storage is quite easy.
You click a few buttons, type a few strings and you’re done.
Authentication:Firebase has up to nine authentication providers (email/password, Facebook, Twitter, Google, etc), however, we will use email/password authentication for this project.
Simply enable and save the email/password provider from the authentication menu on Firebase console.
Firebase authentication providersDatabase:In the Database section, click the Create database button for Cloud Firestore.
Select a starting mode for your Cloud Firestore Security Rules: there are two modes (Test mode and Locked mode).
Test mode allows reads and writes access to everyone whereas Locked mode denies all reads and writes from mobile and web clients.
For now, select Test mode.
Modify the security rules so that only authenticated users can read and write to your database .
Read more about Cloud Firestore security rules hereCloud Firestore security rulesStorage:Firebase Storage allows storage and retrieval of user-generated files like images, audio, and video without server-side code.
In the Storage section, click the Get Started button and accept the default security rules.
Dependencies:The last step in the setup process is to add authentication, cloud firestore, and firebase storage dependencies to your app-level build.
Thereafter, you can add other dependencies you will need in the project.
It’s more time-efficient that way.
Create signup and login activitiesSignup:Signup activityIn the SignupActivity, retrieve the user’s email and password from the input fields, then pass them tofirebaseAuth.
createUserWithEmailAndPassword() method to create a new user on Firebase.
Within the createUserWithEmailAndPassword() method, verify that the new user was successfully created before calling saving the user’s details to Cloud Firestore.
For this project, I used a HashMap userData containing the user’s details to save the user’s information to Firestore with userID as primary key (Firestore document).
Using userID as key allows for easy query.
Login:Login activityDuring login, Firebase authenticates that the user has signed up and that the login details are correct, else it will throw up an error.
To sign in user with email/password, call auth.
signInWithEmailAndPassword() method and pass on the user’s email and password for authentication.
Finally, build your chatroomMainActiviyWhen it comes to user-friendliness, simplicity is always the best route to follow.
Therefore, our chatroom would have only the basic and most needed features: aRecyclerViewto display messages, EditText to type in messages,FloatingActionButton to send messages and a ProgresBar to display when messages are loading.
Chatroom layoutDesign the list item(s):This list item contains the views that will be displayed in the RecyclerView.
A chatroom’s list item will typically consist of anImageView to display the profile picture, TextView for the username, date/time, and message, and a couple of other features that are important to the users or app functionality.
For this project, I created two types: one for messages_in and another for message_out.
List item designCreate Message model classThe Message model class represents the properties of a message posted in the forum.
The object of this class is what will be stored in the messages collection of your database.
Declare the variables in your Message class, and add getters and setters as shown below.
Create FirestoreRecyclerAdapter:FirestoreRecyclerAdapter binds a Query to theRecyclerView such that whenever messages are added, removed, or changed in the chatroom, these updates are automatically applied to the RecyclerView in real time.
Creating a the adapter involves three steps: First, create an object of RecyclerView.
ViewHolder which holds the message items within the RecyclerView.
It can be an inner class of the adapter class or a separate class entirely.
The next step is to configure your FirestoreRecyclerAdapter to build FirestoreListOptions.
The last step in creating the adapter is to override onCreateViewHolder(), onBindViewHolder(),and getViewItemType() methods.
The getViewItemType() method sets the item’s view type.
A typical chatroom will have two view types: one for current user’s message and the other for messages from other users.
The onCreateViewHolder() method is called when the RecyclerView needs a new RecyclerView.
ViewHolder while theonBindViewHolder() method binds the corresponding values fromMessage object to the RecyclerView.
The process of binding values to the views is repeated for each message that will be displayed.
You have finished creating your adapter class, so go over to MainAcivity and set MessageAdapter as the adapter for yourRecyclerView.
Finally, attach anOnClickListener to the FloatingActionButton so it will listen for clicks and save the message to Firestore whenever the button is clicked.
Congratulations on completing the article.
I hope it has been helpful in building your real-time android chatroom.
If you have any queries, do post them in the comments section below.
I have added the link to the project github repo below.
megamendhie/Soccer-GistDiscussion room app developed to show how to build real-time android chatroom with Firebase.