Skip to content Skip to sidebar Skip to footer

Is There A Way To Write This Database Call Into A Function Easily?

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('kCreateNewAccoun

Solution 1:

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

  1. Create Interface for callback

    publicinterfaceOnCompleteListener {
         voidonComplete(String text);
     }
    
  2. Create method for fetching text via document name

    publicvoidgetText(Stringdocument, final OnCompleteListener onCompleteListener) {
             db.collection("language").document(document).get()
                     .addOnSuccessListener(newOnSuccessListener<DocumentSnapshot>() {
                         @OverridepublicvoidonSuccess(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", newOnCompleteListener() {
                 @OverridepublicvoidonComplete(String text) {
                     createAccount.setText(text);
                 }
             });
    

Post a Comment for "Is There A Way To Write This Database Call Into A Function Easily?"