1

All of the text in an application I'm working on is stored inside FireStore documents, so to retrieve it I use this bit of code

db.collection("language").document("kCreateNewAccount").get()
  .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
      @Override
      public void onSuccess(DocumentSnapshot documentSnapshot) {
           String viewText = lan.equals("en") ? documentSnapshot.getString("en")
                                              : documentSnapshot.getString("es");
           createAccount.setText(viewText);
      }
  });

I've tried to put it into a function that takes the document name as a parameter and returns the correspondent string to avoid writing the same thing over and over again, to no avail, any help is welcome

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58
  • 3
    Firestore queries are asynchronous. You won't be able to simply wrap it into a function that directly returns the result. The wrapper function will itself have to be asynchronous and accept a callback function like Firestore query. (Otherwise you would block the calling thread, which is almost always bad idea on Android.) – Doug Stevenson Jun 20 '20 at 06:23

1 Answers1

1

Firebase queries are async, you have to use a callback function.

  1. Create Interface for callback

     public interface OnCompleteListener {
         void onComplete(String text);
     }
    
  2. Create method for fetching text via document name

     public void getText(String document, final OnCompleteListener onCompleteListener) {
             db.collection("language").document(document).get()
                     .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                         @Override
                         public void onSuccess(DocumentSnapshot documentSnapshot) {
                             String viewText = lan.equals("en") ? documentSnapshot.getString("en")
                                     : documentSnapshot.getString("es");
                             onCompleteListener.onComplete(viewText);
                         }
                     });
         }
    
  3. Call the method with your document name and specifying a listener

     getText("kCreateNewAccount", new OnCompleteListener() {
                 @Override
                 public void onComplete(String text) {
                     createAccount.setText(text);
                 }
             });
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
arnabxm
  • 149
  • 7