有没有一种方法可以轻松地将此数据库调用写入函数? [英] Is there a way to write this database call into a function easily?

查看:45
本文介绍了有没有一种方法可以轻松地将此数据库调用写入函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的应用程序中的所有文本都存储在FireStore文档中,因此要检索它,我使用以下代码

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

推荐答案

Firebase查询是异步的,您必须使用回调函数.

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

  1. 创建回调接口

  1. Create Interface for callback

 public interface OnCompleteListener {
     void onComplete(String text);
 }

  • 创建用于通过文档名称提取文本的方法

  • 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);
                         }
                     });
         }
    

  • 使用您的文档名称并指定一个侦听器来调用该方法

  • Call the method with your document name and specifying a listener

     getText("kCreateNewAccount", new OnCompleteListener() {
                 @Override
                 public void onComplete(String text) {
                     createAccount.setText(text);
                 }
             });
    

  • 这篇关于有没有一种方法可以轻松地将此数据库调用写入函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆