Home Android & Kotlin Books Saving Data on Android

17
Managing Data with Cloud Firestore Written by Dean Djermanović

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

In the previous chapter, you learned the basics of Cloud Firestore. You learned what Firestore is, how it differs from Realtime database, and how it structures its data. In this chapter, you’ll integrate Firestore into the app. You’ll refactor the current WhatsUp app to use the Firestore as the backend. All of the functionality of WhatsUp app will remain the same. In the process, you’ll learn how to add data to the Firestore, how to update and delete data, and how to use Firebase console to manage Firestore data.

Getting started

You need to set up Firestore before you can start using it. If you followed along with Realtime database chapters, you have already created the project in the Firebase console. If you didn’t, go back to the “Chapter 11: Firebase overview” and “Chapter 12: Introduction to Firebase Realtime Database” to see how to create the project in the console and how to connect your app with Firebase.

Creating the database

Open your WhatsUp project in the Firebase console. Select Database from the menu on the left. You’ll see this screen:

Configuring application

You have created the database in the console. Now you need to configure your app so it can communicate with the database.

implementation 'com.google.firebase:firebase-firestore:20.1.0'
private val database = FirebaseFirestore.getInstance()

Writing data

The first part of the app that you’ll refactor to use Firestore is writing. Instead of writing data to Realtime Database you’ll write the data to the Cloud Firestore.

val documentReference = database.collection(POSTS_COLLECTION).document() //1

val post = HashMap<String, Any>() //2
//3
post[AUTHOR_KEY] = authenticationManager.getCurrentUser()
post[CONTENT_KEY] = content
post[TIMESTAMP_KEY] = getCurrentTime()
post[ID_KEY] = documentReference.id
//4
documentReference
  .set(post)
  .addOnSuccessListener { onSuccessAction() }
  .addOnFailureListener { onFailureAction() }
cloudFirestoreManager.addPost(postMessage, ::onPostAddSuccess, ::onPostAddFailed)

Transactions

Firestore supports another way of writing data, transactions. Transactions are used in cases when you want to write a bunch of data to the database at once. While the transaction is executing, the user won’t be able to read that partially changed state. If one of the operations that are executed in a transaction fails, none of them will be applied because that could potentially leave the database in an inconsistent and undesired state. Either all are applied or none. One transaction operation can write to 500 documents maximally.

Updating data

Next, you’ll add an update feature to your app. You’ll see that it’s very similiar to what you did when adding new data. Open the CloudFirestoreManager class and replace the TODO inside the updatePostContentwith the following:

//1
 val updatedPost = HashMap<String, Any>()

 //2
 updatedPost[CONTENT_KEY] = content

//3
database.collection(POSTS_COLLECTION)
  .document(key)
  .update(updatedPost)
  .addOnSuccessListener { onSuccessAction() }
  .addOnFailureListener { onFailureAction() }
cloudFirestoreManager.updatePostContent(
  post.id,
  postText.text.toString().trim(),
  ::onPostSuccessfullyUpdated,
  ::onPostUpdateFailed
)

Deleting data

One last bit of functionality that you’ll add in this chapter is post deleting. Open the CloudFirestoreManager class and replace the TODO inside deletePost function with the following:

database.collection(POSTS_COLLECTION)
  .document(key)
  .delete()
  .addOnSuccessListener { onSuccessAction() }
  .addOnFailureListener { onFailureAction() }
cloudFirestoreManager.deletePost(post.id, ::onPostSuccessfullyDeleted, ::onPostDeleteFailed)

Firebase console

You can do all of these operations that you implemented in this chapter, like adding data, updating and deleting, manually in the Firebase console.

Key points

  • Firestore database is created in the Firebase console.
  • You need to add a Firestore client library for Android to the project in order to use Firestore APIs.
  • You need to initialize a Firestore instance in order to communicate with the database.
  • You call the collection method passing in the collection path to get a reference to the collection at the specified path in the database.
  • You need to create and populate the map of data that you wan’t to save to the database.
  • You call the set method on the document reference that will replace the data in the document if it already exists or it will create it if it doesn’t to save the data to the database. You pass in the map that contains the data that you want to write to that document.
  • Firebase supports transactions which are used in cases when you want to write a bunch of data to the database at once.
  • You call the update method on a document reference to update fields in the document.
  • You call the delete method on a document reference which deletes the document referred to by the reference.
  • Adding, updating and deleting operations are asynchronous.
  • You can use the Firebase console to manage data in the Firestore database.

Where to go from here?

You implemented adding, updating, and deleting functionalities in this chapter and you saw how you can use the Firebase console to achieve that. You can visit the official documentation https://firebase.google.com/docs/firestore/manage-data/add-data to learn more about these operations.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.