CRUD Operations With Firebase Cloud Fire Store

Android
 

Introduction

 
In this article, we will learn how to use Firebase Cloud Fire Store in Android and how to do CRUD operations with Firebase Cloud Fire Store.
 
Getting started with Firebase
 
Read the following to learn how to set up the Firebase in your Android project.
 
Reference - https://androidmads.blogspot.in/2016/10/android-getting-started-with-firebase.html
 
Additionally, do the following for Cloud Firestore.
 
You can enable the test mode to make the database accessible to all users.
 
Android
 
At this point, the empty DB is created as shown in the figure below.
 
Android
 

Firebase Cloud Fire store

 
It is a flexible, scalable NoSQL cloud database to store and sync data for the client- and server-side development.
 
Key capabilities
  • Flexibility
  • Expressive Querying
  • Real-time Updates
  • Offline Support
  • Designed to Scale
Concepts
 
Firestore hosted the data like NoSQL Database.
 
Database             ->            Collections
Table                     ->            Document
Column                ->            Field
 
Coding Part
 
I have split this part into 3 steps as in the following.
  • Step 1 - Creating a New Project with Empty Activity.
  • Step 2 - Setting up the Firebase Library.
  • Step 3 - Implementation of CRUD with Cloud Firestore.
Step 1 - Create a new project with Empty Activity
  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
     
    Android
     
  3. Click the “Finish button to create a new project in Android Studio.
Step 2 - Setting up the Firebase Library
 
In this part, we will see how to set up the library for the project.
  1. Open your project level build.gradle file and add the following lines in dependencies
    1. {  
    2.     …  
    3.     classpath 'com.google.gms:google-services:3.1.0'  
    4.               …  
    5. }  
  1. Then add the following lines in all projects in the project level build.gradle file.
    1. allprojects {  
    2.     repositories {  
    3.         google()  
    4.         jcenter()  
    5.         maven {  
    6.             url "https://maven.google.com"  
    7.         }  
    8.     }  
    9. }  
  1. Then add the following lines in app level build.gradle file to apply Google services to your project.
    1. dependencies {  
    2.     ...  
    3.     implementation 'com.google.firebase:firebase-firestore:11.8.0'  
    4. }  
  1. Then click “Sync Now” to set up your project.
Step 3 - Implementation of CRUD with Cloud Firestore
 
In this part, we will see how to implement CRUD operations with Firestore.
 
First, we will initialize the Firestore Database.
  1. FirebaseFirestore myDB;  
  2. // Init FireStore  
  3. myDB = FirebaseFirestore.getInstance();  
INSERT DATA
 
You can insert the data to Firestore like the following.
  1. Map<String, Object> data = new HashMap<>();  
  2. data.put("task_name", edtData.getText().toString());  
  3. myDB.collection("tasks")  
  4.         .add(data)  
  5.         .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {  
  6.             @Override  
  7.             public void onSuccess(DocumentReference documentReference) {  
  8.                 toastResult("Data added successfully");  
  9.             }  
  10.         })  
  11.         .addOnFailureListener(new OnFailureListener() {  
  12.             @Override  
  13.             public void onFailure(@NonNull Exception e) {  
  14.                 toastResult("Error while adding the data : " + e.getMessage());  
  15.             }  
  16.         });  
Here, we created a collection named “tasks” and we inserted the data with “task_name”. The add() method automatically generates and assigns a unique alphanumeric identifier to every document it creates. If you want your documents to have your own custom IDs instead, you must first manually create those documents by calling the document() method, which takes a unique ID string as its input. You can then populate the documents by calling the set() method, which, like the add method, expects a map as its only argument.
 
You can set user preferred document name instead of auto generated unique identifier using the following method
  1. myDB.collection("tasks").document("user_preferred_id").set(data)  
The following figure shows the DB after inserting the data.
 
Android
 
READ DATA
 
You can read the collection of data from firestore using “addSnapShotListener”. The code explains how to read data from Cloud Firestore.
  1. myDB.collection("tasks").addSnapshotListener(new EventListener<QuerySnapshot>() {  
  2.         @Override  
  3.         public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {  
  4.             if (e != null)  
  5.                 toastResult(e.getMessage());  
  6.             list.clear();  
  7.             for (DocumentSnapshot doc : documentSnapshots) {  
  8.                 list.add(doc.getString("task_name"));  
  9.             }  
  10.         }  
  11.     });  
UPDATE DATA
 
You can update the record in the collection if you know the name/Id of the document. The following code shows how to update the data. Map is used to update the data with the same in the document.
  1. Map<String, Object> data = new HashMap<>();  
  2. data.put("data", edtData.getText().toString());  
  3. myDB.collection("myData").document("1").update(data)  
  4.         .addOnSuccessListener(new OnSuccessListener<Void>() {  
  5.             @Override  
  6.             public void onSuccess(Void aVoid) {  
  7.                 toastResult("Data updated successfully");  
  8.             }  
  9.         })  
  10.         .addOnCompleteListener(new OnCompleteListener<Void>() {  
  11.             @Override  
  12.             public void onComplete(@NonNull Task<Void> task) {  
  13.                 toastResult("Data update Completed");  
  14.             }  
  15.         })  
  16.         .addOnFailureListener(new OnFailureListener() {  
  17.             @Override  
  18.             public void onFailure(@NonNull Exception e) {  
  19.                 toastResult("Error while updating the data : " + e.getMessage());  
  20.             }  
  21.         });  
DELETE DATA
 
The existing data can be deleted from Firestore using delete() function. The following code shows how to implement the delete function.
  1. myDB.collection("myData").document("1").delete()  
  2.     .addOnSuccessListener(new OnSuccessListener<Void>() {  
  3.         @Override  
  4.         public void onSuccess(Void aVoid) {  
  5.             toastResult("Data deleted successfully");  
  6.         }  
  7.     })  
  8.     .addOnFailureListener(new OnFailureListener() {  
  9.         @Override  
  10.         public void onFailure(@NonNull Exception e) {  
  11.             toastResult("Error while deleting the data : " + e.getMessage());  
  12.         }  
  13.     });  
Download Code
 
If you think this article is informative do like and star the repo in GitHub. You can download the full sample code here.
 
Demo
 
You can find the demo video on YouTube.


Similar Articles