此函数返回消息,它返回null我需要解决方案以返回值谢谢
public String saveData(final User user) {
final String[] message = new String[1];
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword(user.getEmail().toString(), user.getPassword().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
message[0] = "Fail" + e.getMessage();
}
});
return message[0];
}
答案 0 :(得分:0)
问题在于firebaseAuth.createUserWithEmailAndPassword()
是异步操作-因此onSuccess()
和onFailure()
回调将在以后不久触发。但是开始操作后您将立即返回message[0]
-这就是为什么您获得null
结果的原因。
为了解决该问题,您可以将回调作为参数传递给函数,并在触发回调时处理结果。例如,
public void saveData(final User user, OnSuccessListener<AuthResult> success, OnFailureListener failure) {
final String[] message = new String[1];
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword(user.getEmail().toString(), user.getPassword().toString())
.addOnSuccessListener(success).addOnFailureListener(failure);
}
并调用它
saveData(user, new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
// TODO handle result
}
}, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
String message = "Fail" + e.getMessage();
}
});
类似的东西。