android - 如何从 FireStore 获取数据到自定义对象然后返回?

标签 android google-cloud-firestore

当我运行此方法时返回 V = null,考虑到 onComplete(... 中的 V,其 not null

公共(public)静态车辆 v;

public static Vehicle tessst() {

    v = new Vehicle();

    DocumentReference docRef = db.collection("vehicles").document("123");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

            if(task.isSuccessful()){
               DocumentSnapshot documentSnapshot = task.getResult();
                if(documentSnapshot !=null){
                    v  = documentSnapshot.toObject(Vehicle.class);
                }
            }
        }
    });
      return  v;
}

最佳答案

Firebase Firestore get() 方法异步获取并返回对象,这意味着按时间顺序发生以下情况:

  1. return v; 语句会先执行
  2. 然后 get() 获取文档详细信息并分配给 v = documentSnapshot.toObject(Vehicle.class);

因此,与其使用 return v; 从方法中返回对象 v,不如调用一个 listener 并在它返回后设置对象 v从 Firestore 获取。

您还可以使用LiveData 将从 Firestore 获取的新数据发送到您的 Activity 或 fragment ,而不是使用监听器。

public static Vehicle v;

// method return type changed to void
// public static Vehicle tessst() {
public static void tessst() {

    v = new Vehicle();

    DocumentReference docRef = db.collection("vehicles").document("123");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

            if(task.isSuccessful()){
                DocumentSnapshot documentSnapshot = task.getResult();
                if(documentSnapshot !=null){
                    v  = documentSnapshot.toObject(Vehicle.class);

                    // TODO
                    // mListener will be called from here 
                    // or 
                    // set the value of the liveData here
                    // to send the object v obtained 

                }
            }
        }
    });
    // return v;
}

关于android - 如何从 FireStore 获取数据到自定义对象然后返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708314/

相关文章:

java - 在布局中,如何增加 Switch 文本周围的填充,使文本适合 Switch?

node.js - Firestore 安全规则 : How to enforce the number of fields CREATED in a Firestore document thru security rules?

java - Android - Firestore 使用 startAfter() 和 limit() 返回一个空查询

ios - 将 Firebase 文档计数返回为表格行计数

flutter - 如何通过Flutter中的云功能从Firestore获取documentSnapshot?

android - 如何只显示位图的一部分——

java - 如何将java项目集成到现有的Android Studios项目中

android - 如何在不丢失纵横比的情况下缩放方形图像(即使布局不是方形的)

android - 如何使用 Fiddler 通过 Android 模拟器跟踪 https url?

node.js - 从 firestore 获取数据时使用 async forEach 循环