所以我遇到的问题是,在Firestore db.collection.get()查询完成执行之前,loadUserNameFromFirestore()方法将执行return语句。我已将日志放在firestore db.collection.get()查询之后,方法return语句之前。
private String loadUserNameFromFirestore(Appointment appointment) {
final StringBuilder userFullName = new StringBuilder();
String userUid = appointment.getAppointment_doctor_uid();
db.collection(Constants.FIRESTORE_DOCTOR).document(userUid)
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot documentSnapshot = task.getResult();
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_TITLE)).append(" ");
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_FNAME)).append(" ");
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_LNAME));
Log.d("DEBUG_APP", userFullName.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
Log.d("DEBUG_APP", "Final: " + userFullName.toString());
return userFullName.toString();
}
下面是根据上述代码创建的日志。
10-03 02:43:30.561....: Final:
10-03 02:43:31.044....: Dr Naila Alam
如上所示,首先执行了return语句“ First:”之前的日志,然后执行了Firestore查询“ Dr Naila Alam”之后的日志。
有没有办法确保在Firestore完成执行后才调用return语句。我真的很感谢您的帮助。
答案 0 :(得分:0)
如您所见,您对firebase的请求是异步操作,因此代码不必等待它完成,而是继续其路由。 您附加的侦听器在另一个线程上工作,因此您的GUI不会冻结。这就是为什么您不能运行通过Firebase调用返回值的方法的原因。
必须修改,以调用方法来检索值,并在onComplete方法中调用另一个方法来设置获取的值。
例如:(假设您需要用户名才能在GUI上显示它)
public void setTextUsername(String username)
this.textViewUsername.setText(username);
//here you can do all you need with username value
}
public void loadUserNameFromFirestore(Appointment appointment){
String userUid = appointment.getAppointment_doctor_uid();
db.collection(Constants.FIRESTORE_DOCTOR).document(userUid)
.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(@NonNull Task<DocumentSnapshot> task) {
StringBuilder userFullName = new StringBuilder();
DocumentSnapshot documentSnapshot = task.getResult();
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_TITLE)).append(" ");
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_FNAME)).append(" ");
userFullName.append(documentSnapshot.getString(Constants.FIRESTORE_STAFF_LNAME));
Log.d("DEBUG_APP", userFullName.toString());
setTextUsername(userFullName.toString());
}})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
如果您不清楚什么地方,请不要犹豫。我很乐意提供帮助!