Firebase MVVM Example – Implementing Authentication

Recently we finished learning the MVVM Design Pattern in Android App Development, and while learning that we used RESTful APIs to communicate with our Back End. But sometimes we do create server less application using …

Firebase MVVM Example

Recently we finished learning the MVVM Design Pattern in Android App Development, and while learning that we used RESTful APIs to communicate with our Back End. But sometimes we do create server less application using Firebase. And some people asked that “How do I follow MVVM when using Firebase?“.  That is why in this Firebase MVVM Example we will learn implementing the Firebase Authentication with MVVM Design Pattern.

Prerequisites

If you are an absolute newbie and accidentally came here then, I would like to tell you that this post is not for you. Before moving ahead in this post you should already know these things.

  1. What is MVVM Design Pattern?
  2. How to implement Firebase Authentication

If you don’t know these things, then take your time and go through the above courses first. Then you can follow this. And if you are brave enough to follow it without the above mention courses, then that’s awesome let’s start. And one thing I forgot, we also need a little bit of RxJava and RxAndroid.

Creating an Android Project

As always we need to create a new Android Studio Project. Here, I am creating a project named “Firebase Auth MVVM”. You can change the name if you want. But make sure you have the following settings while creating the project.

Firebase MVVM Example
Firebase MVVM Example

Once your project is loaded, we will start adding the required dependencies.

Adding Required Dependencies

First add the following in your app level build.gradle file. You need to add all these lines inside dependencies block.

As you can see we are going to use ViewModel, LiveData, Material Design, Kodein Dependency Injection and RxJava. But other than all these dependencies, the most important thing that we need is the Firebase. And we did not add this yet. But don’t worry sync the project for now.

Adding Firebase Authentication

Now adding firebase is very easy and I already discussed it many times in videos and post. So I think no point of explaining the same thing again and again. You can go to Tools -> Firebase to add firebase authentication in Android Studio. Still you have confusion then you can just check this link where I added Firebase Cloud Messaging. But you don’t need to add cloud messaging, you need to add Authentication. So just select Authentication instead of Cloud Messaging and the process is same.

Enabling Data Binding

As we are going to implement the Model View ViewModel design pattern and data binding is a key point of this pattern. So let’s enable data binding.

  • Again go to app level build.gradle file and enable data binding by adding following code inside android block.

  •  After this inside the file gradle.properties add this line at the bottom.

  • Now finally sync your project and we are good to go.

Creating Packages

Organizing the codes in different packages properly is very important thing, if you don’t want to bang your head, when you need to open different files of your project. haha 😀 . So first we will create the following package structure in our Android Studio. Just to make the things well organized.

Firebase MVVM Example
Firebase MVVM Example

As you can see I have created thre main packages

  1. data: Inside this package we will store the models and the repositories. So again we have two more packages inside this package.
  2. ui: All the UI related things will go inside this package (Activities, Fragments, ViewModels, Adapters etc). Inside this package we have two more packages for the Auth and for the Home screen of our application.
  3. utils: Inside this package we will store the helper functions.

Now finally refactor your MainActivity as LoginActivity and activity_main.xml as activity_login.xml. Because the MainActivity is our LoginActivity and changing a sensible name is always a good idea. So refactor both xml and kotlin file for the activity and we are good to go.

Creating Activities

In this project we basically need three activities. For Login, for Signup and for Home. We already have the Login and we need to create the Home and the Signup Activity. So create empty activities in Auth and Home Package as shown in the below image.

Firebase MVVM Example
Firebase MVVM Example

So when the user is authenticated either from Login or Signup activity, we will display the HomeActivity.

According to the MVVM Design Rule, our View can communicate with ViewModel, ViewModel can communicate with Repository and Repository can communicate with our Back End, which is in this case Firebase.

So first we will create a Firebase class to handle Firebase operations.

Creating Firebase Source

  • Inside your data package create one more package named firebase. And inside this package create a class named FirebaseSource.

  • As you can see in the above class we have 3 functions, for login, signup, logout and getting the currently logged in user. The code is pretty much self explanatory, and it is almost the same as we do with Firebase. The only difference here is, we are using Completable that is an RxJava class.  Completable basically means it holds something that will complete and we can get an indication when it is completed or failed. And it is the perfect class to use with FirebaseAuth because auth is a network operation that will complete and we need to know if it is completed or failed.
  • So here we are creating a Completable and inside the completable we are performing the authentication. Once it is completed we are using the emitter to indicated that the task is completed or failed. Fairly simple, I guess. 

So we have the FirebaseSource, and now we need a Repository so that we can communicate with the Firebase.

Creating User Repository

  • Inside the repositories package (which is inside data) create a new class named UserRepository. To the constructor of this class we will pass the FirebaseSource that we just created. And then with the help of firebase source, we will perform the operations needed.

  • As you can see the code is very simple. We are just calling the functions, that we defined inside FirebaseSource.
  • Now we have the repository that will communicate with our backend. And we need a ViewModel that can communicate with the Repository.

But we also need an AuthListener here so that when the task is finished we can fire a callback inside our Activity, to determine what happened to the login or signup operation. 

Creating an AuthListener

  • Inside the auth package (that is inside ui) create an interface named AuthListener.

  • Now we will create our ViewModel.

Creating AuthViewModel and Factory

AuthViewModel

  • Again inside the auth package create a new class named AuthViewModel.

  • And we have the ViewModel, now we just need to use DataBinding with our Activity.

AuthViewModel Factory

  • As we need the UserRepository inside the AuthViewModel we need a ViewModelFactory to generate the ViewModel with the required parameter.
  • So create one more class named AuthViewModelFactory inside the auth package.

Designing UI and Binding Data

Login Activity

  • Go inside your activity_login.xml and paste the following code.

  • The above XML code will generate the following layout.
Firebase Authentication MVVM
Firebase Authentication MVVM

But I have used some drawable resources to design the above layout. And after copying and pasting you will see some error that those resources are missing. But don’t worry you can get my source code and all the resources at the end of this post. 

Also make sure inside the data tag, you have given your ViewModel path according to your project. 

Signup Activity

Now we will do pretty much the same thing in SignupActivity as well.

  • First copy the following XML inside activity_signup.xml. 

  • This XML will generate the following design.
Firebase Authentication MVVM
Firebase Authentication MVVM

Again make sure that you have defined the correct path of the ViewModel inside the variable tag. 

We have the design ready, and now we just need to bind the ViewModel and View. But before doing this thing we need one more small thing. When the authentication is successful we need to start the HomeActivity and when the user logs out again we need to start the LoginActivity. And we don’t want to repeat the codes again and again, so for both these operation we will define two extension functions.

Functions for Switching Between Login and Home Activity

  • Create a new kotlin file inside util package and name it ViewUtils.kt.

  • We will use these functions for login and logout.
  • Now we can bind the ViewModel and Activites but before doing that we will use Kodein to create a Dependency Provider.

Creating Dependency Provider using Kodein

As you know, we should not make the classes dependent. And to make the classes independent we need to use the Dependency Injection pattern. And to do this we will be using the Kodein Framework that we already added.

  • So inside your main package create a new class named FirebaseApplication.

  • Now we need to define this class in our AndroidManifest.xml.

  • And we are done.

Binding ViewModel and Activities

LoginActivity

  • Open LoginActivity and write the following code.

  • The code is very simple and straightforward, in case you are having trouble understanding anything, please comment.

Signup Activity

  • Now we will do the same thing inside SignupActivity as well.

  • Now we just need to work on HomeActivity.

Finishing Up Home Activity

Creating HomeViewModel and HomeViewModelFactory

  • First create HomeViewModel inside the home package.

  • Again we need to create our ViewModelFactory because we are passing repository to the HomeViewModel. So create one more class named HomeViewModelFactory.

  • And that’s it. Now let’s code the XML part of our HomeActivity.

Designing UI

  • Go inside activity_home.xml and write the following code.

  • Again make sure you have given the correct path of the HomeViewModel inside the variable tag. 

Binding HomeViewModel and HomeActivity

  • Again we will do the same thing, that we did for Login and Signup activity.

  • And we are done. You can try running the application and it should work fine. For example you can check my APK to test, if yours is not working.

Download APK

Firebase MVVM Example Source Code

In case you are not able to follow through the tutorial, don’t worry you have my source code to cross check your project. And if still having problem comment below and I will try to help you out.


git hub repository
Get the Source Code

So that is all for this Firebase MVVM Example friends. I hope I taught you something new with this post. And if you think it is really useful then please support me by sharing this post with your friends. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x