Home > Software design >  Accessing same Firebase Firestore in multiple fragments
Accessing same Firebase Firestore in multiple fragments

Time:03-14

I have an ArrayList stored in Firestore.

I have a RecyclerView in Fragment A displaying the basic info of each person. I have an onClickListener that replaces Fragment A with Fragment B and passes off the UID of the Person Item clicked to Fragment B as well. My goal with fragment B is to display all of the details of the Person item clicked (and an option to add some more data) by somehow using the UID to get my data from Firestore. My question is this, should I instantiate a Firebase Firestore for every fragment that I need that same Firestore in? Or can I pass off the Person object as a bundle (though I'm not sure if any changes I make reflect on Firebase). I thought it was a very costly process and I'm not sure what my alternatives are.

CodePudding user response:

You can create a singleton class like this:

public class FirebaseSingleton{
   private static FirebaseFirestore instance;
   public static FirebaseFirestore getInstance(){
      if (instance == null) instance = FirebaseFirestore.getInstance();
      return instance;
   }
}

This will return the same object

CodePudding user response:

  1. FirebaseFirestore is a Singleton class which means that any where you call this:

FirebaseFirestore db = FirebaseFirestore.getInstance();

You will always get the same object.

  1. You can pass off the data to the second fragment if the Person class implements Parcelable. If it implements Parcelable you can add the person object to a bundle and send it to the other fragment this way.

  2. If by "instantiating Firestore" you actually mean retrieving your data from Firestore , Firestore locally caches a copy of the data that your app is using, so fragment B will retrieve the data from the local cache.

  • Related