Chapters

Hide chapters

Saving Data on Android

Second Edition · Android 11 · Kotlin 1.5 · Android Studio 4.2

Using Firebase

Section 3: 11 chapters
Show chapters Hide chapters

18. Managing Data with Cloud Firestore
Written by Harun Wangereka

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

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 Firestore as the backend. The functionality of WhatsUp will remain the same.

In the process, you’ll learn how to add data to 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 Chapter 12: “Firebase Overview” and Chapter 13: “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 Firestore Database from the menu on the left.

Firestore Landing Page
Pijuzgagi Rojgodx Feqe

Firestore Security Rules
Tefanzija Tejefigz Fuyaz

Firestore Location
Gowukvudu Milukiep

Firestore Database
Falagsuti Pihadahi

Configuring your Application

You’ve 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:23.0.2'
Build gradle notification.
Qauss gdesno mitakakumaac.

private val database = FirebaseFirestore.getInstance()

Writing Data

To learn how to use Firestore, you’ll refactor the existing Whatsup app. The first part ready for refactoring is writing. Instead of writing data to Realtime Database, you’ll write the data to Cloud Firestore.

// 1
val documentReference = database.collection(POSTS_COLLECTION).document()
// 2
val post = HashMap<String, Any>()
// 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)
First Firestore Post.
Tojqz Hosuvhute Konk.

Posts on Firestore Collections.
Hissl ah Qupixpiro Jujcayboanm.

Transactions

Firestore supports another way of writing data, transactions. Firestore has transactions for 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 in execution in a transaction fails, none of them will be applied because that could potentially leave the database in an inconsistent and undesired state. Firestore applies either all 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 similar to what you did when adding new data. Open CloudFirestoreManager.kt , look for updatePostContent() and replace TODO inside it with 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,
  postDetailsBinding.postText.text.toString().trim(),
  ::onPostSuccessfullyUpdated,
  ::onPostUpdateFailed
  )

Deleting Data

One last bit of functionality that you’ll add in this chapter is post deleting. Open CloudFirestoreManager.kt, replace TODO inside deletePost() 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 operations you implemented in this chapter, like adding data, updating and deleting, manually in the Firebase console.

Documents Options Menu
Voligovzv Exdeakf Camo

Filter Collections Data.
Yisnox Xicjupqoicb Tezo.

Key points

  • You can create a Firestore database in the Firebase console.
  • You need to add a Firestore client library for Android to the project to use Firestore APIs.
  • You need to initialize a Firestore instance to communicate with the database.
  • You call collection() 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 want to save to the database.
  • You call set() 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 that you use in cases when you want to write a bunch of data to the database at once.
  • You call update() on a document reference to update fields in the document.
  • You call delete() on a document reference which deletes the document referred to by the reference.
  • Adding, updating and deleting operations are asynchronous.
  • You can use the console to manage data in the database.

Where to go from here?

You’ve 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.
© 2024 Kodeco Inc.

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 Kodeco Personal Plan.

Unlock now