按照我在这里创建的上一个线程:
How do I set a variable inside of an onComplete method?
我仍在尝试调用我在内部设置的变量
onComplete
方法。我知道在访问该方法之间存在延迟。向我提出的一个解决方案是创建一个界面。虽然我已经成功实现了接口,但我不确定我的实现是否正确,因为我仍然会得到null。
这是我的界面:
public interface MyCallBack {
void onCallFullName(String fullName);
void onCallEmail(String Email);
}
从firebase获取数据的方法:
private void callUserCredential(MyCallBack myCallBack) {
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
String userID = fAuth.getCurrentUser().getUid();
DocumentReference docRef = fStore
.collection("users")
.document(userID);
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 for successfully fetching data from firebase
Log.d(TAG,"User full name: " + document.getString("FullName"));
Log.d(TAG, "User email: " + document.getString("Email"));
String fullName = document.getString("FullName");
String eMail = document.getString("Email");
//Log for successfully setting the data into the variables
Log.d(TAG, "donorFullName set: " + fullName);
Log.d(TAG, "donorEmail set: " + eMail);
//Interface callback
myCallBack.onCallFullName(fullName);
myCallBack.onCallEmail(eMail);
}
}
}
});
}
最后,我调用接口:
//Create booking information
BookingInformation bookingInformation = new BookingInformation();
callUserCredential(new MyCallBack() {
@Override
public void onCallFullName(String fullName) {
donorFullName = fullName;
}
@Override
public void onCallEmail(String Email) {
donorEmail = Email;
}
});
//Log for successfully calling the interface
Log.d(TAG, "donorFullName bookingInformation: " + donorFullName);
Log.d(TAG, "donorEmail bookingInformation: " + donorEmail);
bookingInformation.setDonorName(donorFullName);
bookingInformation.setDonorEmail(donorEmail);
logcat仍然显示相同的内容: