当我运行此方法时返回 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()
方法异步获取并返回对象,这意味着按时间顺序发生以下情况:
return v;
语句会先执行- 然后
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/