Is there a way to write this database call into a function easily?

假如想象 提交于 2021-01-28 14:09:10

问题


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


回答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);
                 }
             });
    


来源:https://stackoverflow.com/questions/62482282/is-there-a-way-to-write-this-database-call-into-a-function-easily

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!