Lesson 9. Firebase: auth, db & storage

In this lesson you'll learn about Android's integration with Firebase.

Micro Sprint 7
Activity Type Lesson
Expected Duration 30 minutes
Topic Fragments
Objective Learn about Firebase integration.

1. Introduction

As seen on Firebase Documentation

Firebase helps you build better mobile apps, without managing infraestructure. Providing on-demand services such as databases, analytics, messaging and authentication, Firebase lets you focus on your app and on your users. It is built on top of Google's Cloud Platform and can scale automatically as much as you need it to.

2. Installing Firebase on your project

First of all, open the Firebase asistant to your IDE by going to Android Studio, clicking tools and then Firebase. From that pane you can interact and install the different services provided by following the on-screen instructions.

3. Available libraries

Gradle Dependency Line Service
com.google.firebase:firebase-core:17.0.0 Analytics
com.google.firebase:firebase-database:18.0.0 Realtime Database
com.google.firebase:firebase-firestore:21.2.1 Cloud Firestore
com.google.firebase:firebase-storage:18.0.0 Cloud Storage
com.crashlytics.sdk.android:crashlytics:2.10.1 Crashlytics
com.google.firebase:firebase-auth:18.0.0 Authentication
com.google.firebase:firebase-messaging:19.0.0 Cloud Messaging
com.google.firebase:firebase-config:18.0.0 Remote Config
com.google.firebase:firebase-ads:18.0.0 AdMob
com.google.firebase:firebase-appindexing:19.0.0 App Indexing
com.google.firebase:firebase-perf:18.0.0 Performance Monitoring

4. Setup Firebase Authentication

Firebase can manage your users authentication with Google, Facebook, Twitter, GitHub, Phone and even your custom auth provider. To use it you must add the Authentication dependency on your build.gradle

implementation 'com.google.firebase:firebase-auth:18.0.0'

The FirebaseAuth instance from FirebaseAuth.getInstance() offers your several methods in order to sign in, sign up and even delete users. With this object you can user several authentication providers, and then in the web console -inside firebase- you can manage them.

In order to sign up new users with e-mail and password, you can use the following method:

auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "createUserWithEmail:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "createUserWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
                updateUI(null)
            }

            // ...
        }

To sign them in, you use:

auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInWithEmail:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
                updateUI(null)
            }

            // ...
        }

5. Cloud Firestore

Firebase Firestore is a cloud storage functionality inside Firebase which allows you to handle and save your data in a document-collection-oriented manner. To get more information about how it handles data, visit Firebase Firestore

To use Firestore inside your proyect, you must add the Firestore dependency on your build.gradle file:

implementation 'com.google.firebase:firebase-firestore:21.2.1''

To initialize an instance of Firestore:

val db = FirebaseFirestore.getInstance()

To add data you use Collections and Documents, Firestore creates the documents and collections the first time you add data to the document:

// Create a new student with a first and last name
val student = hashMapOf(
        "first" to "Vivian",
        "last" to "Gomez",
        "born" to 1998
)

// Add a new document with a generated ID
db.collection("students")
    .add(student)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Now that you've written some data to your db, you can manage it from the Firebase Console on the web. To read the data you can use the get method to retrieve the object or entire collection:

db.collection("students")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents.", exception)
        }

if you want to read more about Firestore, please read the documentation.

6. Firebase Cloud Storage

Firebase Storage is a Cloud service included in Firebase. It lets you handle file uploads and downloads with ease and secutiry. To use it you must add the dependency on your build.gradle file:

implementation 'com.google.firebase:firebase-storage:19.1.0

To initialize an instance you must:

val storage = FirebaseStorage.getInstance()

Now that you have an instance you can start uploading and downloading files from the server.

To upload a file:

// Create a storage reference from our app
val storageRef = storage.reference

// Create a reference to "moviles.jpg"
val mountainsRef = storageRef.child("moviles.jpg")

// Create a reference to 'images/moviles.jpg'
val movilesImagesRef = storageRef.child("images/moviles.jpg")

// While the file names are the same, the references point to different files
movilesRef.name.equals(movilesImagesRef.name)    // true
movilesRef.path.equals(movilesImagesRef.path))    // false

Once you have the reference to the file, you just need to use either putBytes(), putFile() or putStream()

To manage uploads, you can use the task returned by these methods:

val uploadTask = storageRef.child("images/moviles.jpg").putFile(file);

// Pause the upload
uploadTask.pause()

// Resume the upload
uploadTask.resume()

// Cancel the upload
uploadTask.cancel()

To download a file (you could just use the absolute url, but in this case we are going to do it programatically):

// Create a storage reference from our app
val storageRef = storage.reference

// Create a reference with an initial file path and name
val pathReference = storageRef.child("images/moviles.jpg")

// Create a reference to a file from a Google Cloud Storage URI
val gsReference = storage.getReferenceFromUrl("gs://bucket/images/moviles.jpg")

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
val httpsReference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20moviles.jpg");

Once you have this reference, you can download the file using the URL.

If you want to read more about Firebase Storage, visit Storage Documentation.


Version Author Date
1.0 Juan Santiago Acevedo March 27, 2018
2.0 Vivian Gómez Cubillos January 29, 2020

results matching ""

    No results matching ""