Firebase Tutorial for Android: Getting Started

In this Firebase Tutorial for Android you’ll learn how to work with Realtime Databases and Authentication by creating a Joke Telling app. By Filip Babić.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 4 of this article. Click here to view the first page.

Planning our stand-up

By the end of this tutorial you’ll have an app which serves other people the best jokes the internet has ever read! To achieve this, you first need to be able to manage users. The first thing on your plate is to finish up the authentication part of the app.

After the users make their way to the app, you’ll start patching things together with the realtime database. You’ll store the users in the database so that each user can have a list of his/her favorite jokes. Each joke will have a title, description (the joke itself), the author’s name and id.

To model these entities, you’ll use everything from the model package. You only need a few data classes to achieve this.

So the user will be able to sign up for the application, create jokes and like other jokes. It’s not much, but it’s enough for you to learn how to use Firebase as a mini backend.

Hiring comedians

What good is a joke app if there are no comedians – absolutely pun. Good thing you aren’t hiring me! You really need people who actually have a sense of humor. Recruit them and sign them up through Firebase Authentication!

Start by having a look at the RegisterActivity screen and it’s content.

Register Activity

It has a few input fields you need to create a unique user. Since you’re building an authentication service using an email and a password, the user needs to provide them while signing up. Additionally, each user will have a username that you’ll display next to each joke.

In order for your application to use email registration, you need to enable the “email sign-in” method in the Firebase console.

Open up the Firebase Console, click on the Authentication option on the left under Develop and choose the Sign-in Method tab. Now, select the Email/Password provider and enable it.

Yay! You can now proceed to the implementation. :]

Preparing the stage

To connect to Firebase’s authentication service, first, go to the di package and add a class called FirebaseModule.kt to the module package and provide the FirebaseAuth and FirebaseDatabase dependencies in the module:

@Module
@Singleton
class FirebaseModule {

  @Provides
  fun firebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance()

  @Provides
  fun firebaseDatabase(): FirebaseDatabase = FirebaseDatabase.getInstance()
}

Next, add the module to the InteractionModule.kt list of includes, like so:

@Module(includes = [FirebaseModule::class])
@Singleton
abstract class InteractionModule { ...

Now, if you’re using either FirebaseAuth or FirebaseDatabase, you have them provided in the Dagger graph.

Next, open up the FirebaseAuthenticationManager.kt file in the firebase.authentication package and add a FirebaseAuth property to the constructor like this:

class FirebaseAuthenticationManager @Inject constructor(
private val authentication: FirebaseAuth) : FirebaseAuthenticationInterface

You’ve setup everything to use Firebase-related services, way to go! Next you’ll connect the actual authentication process, so keep up the good work. :]

Gathering the crowd

At last, head over to the register method in the FirebaseAuthenticationManager. It should look something like this:

override fun register(email: String, password: String, userName: String, onResult: (Boolean) -> Unit) {
      
}

The registration process will go like this: once the user’s data is valid and they press the Sign up button, you’ll try to create a unique user with the provided email.

If the email is already in use, Firebase will return an error. If it isn’t, an empty user will be created. Since you’re also collecting a username, you’ll need to create a UserProfileChangeRequest which edits a user to include a username.

After you finish all that, you still need to create a user in the database, since the Authentication and Realtime Database are separate services, and don’t share user objects. You’ll do that later on in the tutorial.

Add the following to the body of your register method:

//1
authentication.createUserWithEmailAndPassword(email, password).addOnCompleteListener {
  //2
  if (it.isComplete && it.isSuccessful) {
    authentication.currentUser?.updateProfile(UserProfileChangeRequest
        .Builder()
        .setDisplayName(userName)
        .build())
    //3
    onResult(true)
  } else {
    onResult(false)
  }
}

Taking each commented section in turn:

  1. This method, like most Firebase methods, returns a Task. A Task is something that you can listen to, for the final result.
  2. Inside the lambda block addOnCompleteListener, you can check whether the result of creating a user was successful and/or completed by using the returned object’s properties.
  3. If the task is successful, you will add a username to the new user and call the onResult callback, saying the user has been successfully created. Any other case will just notify that you didn’t manage to create a user.

A session of comedy

Notice how you’re using the authentication.currentUser property. It’s important to know how the FirebaseAuth service works inside an Android application. As soon as you register or log in, the currentUser is available for use. Basically, Firebase caches your login up until the point where you log out or clear the application’s data. This is called a Session. Although not visible through code, it will be there until you close it.

After logging in once, there is no need to worry about the rest. If the currentUser doesn’t return null, then you’re logged in. It also contains information like the unique user id, email and username. Quite handy when you need it.

Finish up FirebaseAuthenticationManager.kt class by filling in the rest of the implementation as follows:

override fun login(email: String, password: String, onResult: (Boolean) -> Unit) {
    authentication.signInWithEmailAndPassword(email, password).addOnCompleteListener {
    onResult(it.isComplete && it.isSuccessful)
  }
}

override fun getUserId(): String = authentication.currentUser?.uid ?: ""
override fun getUserName(): String = authentication.currentUser?.displayName ?: ""

override fun logOut(onResult: () -> Unit) {
  authentication.signOut()

  onResult()
}

The code above is pretty simple. The getUserId and getUserName methods return the data from the current user. Furthermore, the logOut method closes the current Session and the login method tries to log the user in.

After adding this, you’re able to log out of the app in the Profile tab. Moreover you’re able to log back in at the login screen.

Breaking the ice

Build and Run the App. Open the register screen by clicking the Sign up button. Fill in the form and hit Sign up to create a new user. If everything goes well you should see the following screen:

Main Screen

You managed to register! Quickly open up the Firebase console again, navigate your way to the Authentication tab to see your new user at the Users tab. Right now there is only one user in the application and that is you.