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 3 of 4 of this article. Click here to view the first page.

Making punnections

Only having an email provider is very limiting for your app. Firebase, however, allows you to easily add a social provider as an authentication solution. It’s about as simple as flipping an extra switch in the console. In the same place where you enabled email sign-in, you can enable various other providers like Github, Google, Facebook, Twitter and more. This allows your users to connect multiple accounts to one FirebaseUser.

When a user connects multiple accounts, and logs in with any of them, they enter your application as a single user in the Authentication service. It’s super convenient for your users when your app support multiple login platforms.

Check out this link to see the official documentation for this process.

That concludes the Authentication section. Once again, good job! You’re ready for the next part – the Realtime Database.

Time to shine

Now that you have a line of comedians all waiting to do their own stand-ups, all you need is their jokes. Head over to the Firebase dashboard again, this time to the Database option under Develop. When you open this option, you should get to choose between the Cloud Firestore and Realtime Database like so:

Cloud Store and Realtime Databases

The difference is in the way each stores data and works with data. On one hand the Firestore is like an actual database, it stores files in documents and allows for efficient queries. On the other hand you have the Realtime Database which stores everything as a big JSON object which you read parts of.

For small applications, the latter is simpler to use. It also allows realtime updates (as the name says) which is handy when you’re building applications with feeds or chat rooms. This is the reason you will choose it for this tutorial. It’s not a complex application and it will benefit a lot from the realtime updates.

Blue pill or red pill?

Blue Pill or Red Pill

As mentioned above, choose the Realtime Database. You should see a popup asking you for the type of security rules:

Security Rules Screen

Choose either one, it doesn’t really matter which, since you’ll change the settings anyway. Head over to the Rules tab and paste this:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

What these rules mean is that only people who have been authenticated can read or write data, i.e. only your logged in users. Once you’ve copied and pasted the snippet above, click the Publish button to save the rules. Once you switch back to the Data tab your database will be empty and look like this:

Rules Screen

Press any key to continue

Right now there is no data in the database as you’ve only created it. Once you start pushing the jokes it will be much better. However, to save data you need to understand how data is represented.

I’ve already mentioned that our database choice stores everything in a JSON object. This means that each piece of information has it’s own key. Once you request data at a certain key or “directory” (for example key “user”), you’ll receive what is called a DataSnapshot. A snapshot is the current state of that directory which holds everything under the key “user” in this example. You parse that snapshot to get the value, pretty straightforward! You’ll see how to do this in the next section when you start saving data.

The keys can be custom made or generated by Firebase. Usually you’d just let Firebase generate the keys so you don’t have to worry about that. Once Firebase generates a key, and stores the data, the whole directory gets sorted by a timestamp, starting from the newest items first.

Also ordering is always ascending when you query items. Sadly, Realtime Database doesn’t support descending ordering, for example for the number of likes. Firestore was built in response to this, and supports more query options and also much more. However, that might be another tutorial!

Playing the game

You’ve finally reached the part where you’ll work with data. You’ll start off by finishing the user registration process. Remember how I said you’d have to store the user in the database after registration? Well, open up the FirebaseDatabaseManager under the di/firebase/database folder.

Add a private value to the constructor named database and of the type FirebaseDatabase. Your class definition should look like this:

class FirebaseDatabaseManager @Inject constructor(private val database: FirebaseDatabase) : FirebaseDatabaseInterface

And the following KEYS at the top above the class:

private const val KEY_USER = "user"
private const val KEY_JOKE = "joke"
private const val KEY_FAVORITE = "favorite"

You can now connect to the database and store or read data.

Update the createUser() to be the following to finish up the user creation:

override fun createUser(id: String, name: String, email: String) {
  val user = User(id, name, email)

  database
    .reference        // 1
    .child(KEY_USER)  // 2
    .child(id)        // 3
    .setValue(user)   // 4  
}

You’ll call this method right after signing up a user. Here’s what each line means:

  1. Get a reference to the database, which effectively points to the root of the tree/directory.
  2. From the root directory, open up the “user” directory
  3. Inside the “users” directory, open up the directory which matches the “id” of this particular user
  4. Store a new user in that directory by calling the setValue(user) method

And that’s how you store data! If you want to delete a value somewhere, just call the setValue(null).

So the database is like a big family. There are the parents, and each parent can have a bunch of children.

Build and run the app, logout from the Profile tab if you need to, and try to register a new user. You should see a new entry in the database with the new user’s data, right-away and even without refreshing the Firebase page! Now that’s Realtime! :]

I’ve created a couple of users myself and here is the result:

User Sample

Have a look at the structure of the database. The “user” key has two entries, each of which is a unique user. Each user on the other hand has multiple fields, representing its data.