当我运行此方法returns V = null
时,考虑到onComplete(...
内的V,not null
public static Vehicle 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;
}
答案 0 :(得分:1)
Firebase Firestore get()
方法以异步方式提取并返回对象,这意味着会按时间顺序发生以下情况:
return v;
语句首先执行get()
获取文档详细信息并分配给v = documentSnapshot.toObject(Vehicle.class);
因此,不是使用方法中的return v;
返回对象v,而是应该调用侦听器,并在从Firestore获取对象后设置对象v
。
您还可以使用LiveData 将从Firestore获取的新数据发送到您的活动或片段,而不是使用侦听器。
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;
}