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 WebsiteModel.java to store the fields of Object

package com.putuguna.insertcolldoc;
public class WebsiteModel {
private String name;
private String website;
private String webTopic;
private String idDocument;
public WebsiteModel(String name, String website, String webTopic) {
this.name = name;
this.website = website;
this.webTopic = webTopic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getWebTopic() {
return webTopic;
}
public void setWebTopic(String webTopic) {
this.webTopic = webTopic;
}
public String getIdDocument() {
return idDocument;
}
public void setIdDocument(String idDocument) {
this.idDocument = idDocument;
}
}

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

private void startInsertDataDocumentGeneratedSendiri() {
progressDialog.show();
WebsiteModel model = new WebsiteModel("Droid Newbie","androidbie.com","About Programming");
CollectionReference collectionReference = firebaseFirestore.collection("data");
collectionReference.add(model)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Berhasil Insert Data", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
});
}
view raw InsertData.java hosted with ❤ by GitHub
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 :


private void readData(){
CollectionReference collectionReference = firebaseFirestore.collection("data");
collectionReference.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
progressDialog.dismiss();
if(task.getResult().isEmpty()){
Toast.makeText(MainActivity.this, "Data is empty", Toast.LENGTH_SHORT).show();
}else if(task.isSuccessful()){
WebsiteModel websiteModel = new WebsiteModel();
for(DocumentSnapshot documentSnapshot : task.getResult()){
websiteModel.setIdDocument(documentSnapshot.getId());
websiteModel.setName(documentSnapshot.get("name").toString());
websiteModel.setWebsite(documentSnapshot.get("website").toString());
websiteModel.setWebTopic(documentSnapshot.get("webTopic").toString());
}
modelWebsite.add(websiteModel);
showData();
}else{
Toast.makeText(MainActivity.this, "There is a problem", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
/**
* I iterate the list because i just want to display in ArrayAdapter (String)
*/
private void showData(){
List<String> listDataString = new ArrayList<>();
for (int i = 0; i < modelWebsite.size(); i++) {
listDataString.add("IdDocument : "+modelWebsite.get(i).getIdDocument()+"\n"+
"Name : " + modelWebsite.get(i).getName()+"\n"+
"Website : " + modelWebsite.get(i).getWebsite()+"\n"+
"webTopic : " + modelWebsite.get(i).getWebTopic());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listDataString);
listView.setAdapter(adapter);
}
view raw ReadData.java hosted with ❤ by GitHub
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


private void updateTheData() {
progressDialog.setMessage("Updating Data...");
progressDialog.show();
WebsiteModel model = new WebsiteModel("Droid Newbie (updated)", "androidbie.com (updated)", "About Programming (updated)", modelWebsite.get(0).getIdDocument());
CollectionReference collectionReference = firebaseFirestore.collection("data");
DocumentReference documentReference = collectionReference.document(modelWebsite.get(0).getIdDocument());
documentReference.set(model)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Updating successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
view raw UpdateData.java hosted with ❤ by GitHub
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 :

private void deleteData(){
progressDialog.setMessage("Deleting Data...");
progressDialog.show();
CollectionReference collectionReference = firebaseFirestore.collection("data");
DocumentReference documentReference = collectionReference.document(modelWebsite.get(0).getIdDocument());
documentReference.delete()
.addOnCompleteListener(task -> {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Deleting successfulyy", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
view raw DeleteData.java hosted with ❤ by GitHub
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


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)