Lesson 7. Firebase: auth, db & storage

In this lesson you'll learn about Android 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:19.1.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:

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

To sign them in, you use:

mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

5. Cloud Firestore (beta)

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:

FirebaseFirestore 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
Map<String, Object> student = new HashMap<>();
user.put("first", "Vivian");
user.put("last", "Gomez");
user.put("born", 1998);

// Add a new document with a generated ID
db.collection("students")
        .add(student)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception 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()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

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:

FirebaseStorage 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
StorageReference storageRef = storage.getReference();

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

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

// While the file names are the same, the references point to different files
movilesRef.getName().equals(movilesImagesRef.getName());    // true
movilesRef.getPath().equals(movilesImagesRef.getPath());    // 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:

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
StorageReference storageRef = storage.getReference();

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

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

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference 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 Gomez Cubillos January 29, 2020

results matching ""

    No results matching ""