Wednesday, May 16, 2018

Android Create, Read, Update And Delete Data in Firestore Firebase

The concept of data storage between Firebase and MySQL is different. If MySQL uses query concept (primary key, foreign key, etc), then Firebase not like that. Firebase stores data by Collection and Document.

We can say that collection and document are path of data that has stored in Firebase Firestore. We can name the collection by our selves (write the name whatever you want). Collection define as object or list of our data. Document can name by generate automatically from Firebase OR we also can name it by our selves.

Recommended : How to insert file image into Firebase Storage

This article will show you how to do CRUD (Create, Read, Update and Delete) data in Firebase Firestore.

Create Model Of Object

Before we start to do CRUD, let create one object called to store the fields of Object

After the object was created, next we the function of Create, Read, Update, Remove data into/from Firestore

Insert Data

By using the following code, you can insert data into Firebase Store

When insert data, we use method add() after define its collection and its document. The result of the code above is :

Data has stored into Firestore

Take a look at the image above, Why the field of  idDocument is null?

This is my reason why the field of IdDocument is null :
  • I create field IdDocument of object WebsiteModel for store the Document ID when the data has stored in Firestore
  • So why null? Because when store data to Firestore, we don't know the Document ID that generated by Firebase automatically, we able to know the value of the Document ID when we retrieve the data.
  • Just continue read this article (I guarantee you will understand what I mean)

Display Data

After data was stored, now we have to create new function/method that able to read the data from Firestore, here is the method :

And the result when we successfully displaying the data is :

Result of retrieving the data

As you can see at image above, the idDocument has a value : mZPoPqUkc3ZCFmsC4fEz. That was I said that the value of idDocument will able to see when we successfully retrieve the data from Firestore.

By getting the value of idDocument, now we can do process delete and update the data in Firestore.

Update Data

By using the following code you can update your data properly

The result of the code is :

Updating data
The thing you must remember is, when you try to update data, just use method set(), NOT add(), okay?

Delete Data

Now the last, you can delete your data by using the code below :

The result of the code is :

Result of deleting data

That's all about the steps how to do create, read, update and delete data from/to Firebase Firestore. Thank you.

Related Posts