问题描述
当前,我正在尝试将值传递给 onComplete()
方法内部的String变量.但是,当我尝试在方法之外使用它时,它什么也没传递.
currently I am trying to pass a value to String variables inside of an onComplete()
method. But, when I tried to use it outside of the method, it passes nothing.
这是我的 onComplete
代码:
Here's my onComplete
code:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
Log.d(TAG,"User full name: " + document.getString("FullName"));
Log.d(TAG, "User email: " + document.getString("Email"));
donorFullName = document.getString("FullName");
donorEmail = document.getString("Email");
Log.d(TAG, "donorFullName set: " + donorFullName);
Log.d(TAG, "donorEmail set: " + donorEmail);
}
}
}
});
这是我尝试在 onComplete
之外使用的方法:
And here's me trying to use it outside of onComplete
:
BookingInformation bookingInformation = new BookingInformation();
Log.d(TAG, "donorFullName bookingInformation: " + donorFullName);
Log.d(TAG, "donorEmail bookingInformation: " + donorEmail);
bookingInformation.setDonorName(donorFullName);
bookingInformation.setDonorEmail(donorEmail);
这是我的日志:
推荐答案
OnComplete是回调.它将在将来的某个时间而不是立即被调用.您无法知道什么时候会结束,因为它正在等待某些任务完成.任何需要onComplete结果的代码都需要在onComplete函数中调用,而不是在其他地方调用.
OnComplete is a callback. It will be called at some point in the future, not immediately. You have no way of knowing when that will be, because its waiting for some task to finish. Any code that needs the result of onComplete needs to be called in the onComplete function, not called elsewhere.
这篇关于如何在onComplete方法内设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!