How to listen to Cloud Firestore Document change event in Android

One of the many features of android cloud Firestore database is it real-time data change support.

Imagine you are on a page with RecyclerView that holds items you have added to a database.

If you are using SQLite you need to reload the page before you can see any new data you have added to the database.

Another option is to use the RecyclerView Adapter class method notifyDataChange().

With cloud Firestore, we can retrieve documents using addSnapshotListener() event listener method.

Whenever there is a change in our project Firestore document, the application UI will automatically update base on the recent changes .

CREATE A NEW ANDROID PROJECT

  • Open Android Studio
  • Go to file menu
  • Select  new
  • Enter project name
  • Enter activity name
  • Select Default Activity
  • Click on finish button to create a new android project

activity xml layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/titleinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/title"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/bodyinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/titleinput">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/body"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>


    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@id/bodyinput"
        android:textColor="#ffffff"
        android:text="Submit"/>

</RelativeLayout>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.firestore.FirebaseFirestore;

public class FirestoreActivity9 extends AppCompatActivity {   
    private FirebaseFirestore mDatabase;
    private Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firestore9);
       
        submit = (Button)findViewById(R.id.submit);
        mDatabase = FirebaseFirestore.getInstance();
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocalDate date = LocalDate.now();              
                isTableAvailable(date);
            }
        });
    }

    public void isTableAvailable(Date localDate){      db.collection(Constants.BOOKING_COLLECTION).whereEqualTo("bookedDate", localDate).addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if(e != null){
                    Log.w(TAG, "Fetch error.", e);
                    return;
                }
                List<BookingModel> allRestaurants = new ArrayList<>();
                if (queryDocumentSnapshots != null) {
                    for (QueryDocumentSnapshot child : queryDocumentSnapshots) {
                        //convert to class object
                        allRestaurants.add(child.toObject(BookingModel.class));
                    }
                    tableLiveData.setValue(allRestaurants);
                }

            }
        });
    }
}

Add Dependencies

app/build.gradle

implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-firestore:19.0.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment