我正在尝试创建一个名为sendRegisterUserMessage()的方法,如果数据库中不存在该用户,则将User对象发送到Firebase db。但是,无论如何,该方法始终返回false,尽管在侦听器中找到了对象。
在我的MessageSenderHandler类中:
无论如何,在我的MainActivity中的onCreate()中调用此方法:
MessageSenderHandler.getInstance().sendRegisterUserMessage();
在我的MessageSenderHandler类中:
//Checks if user is Registered- if not it sends a RegisterUser message
public void sendRegisterUserMessage() {
System.out.println("registered: " +DatabaseManager.getInstance().isCurrentUserRegistered()); //This prints false no matter what
if (DatabaseManager.getInstance().isCurrentUserRegistered() == false) {
FirebaseDatabase.getInstance().getReference().child(MessageTypes.REGISTER_USER_MESSAGE).child(
CurrentUser.getInstance().getUserId())
.setValue(
new RegisterUserMessage()
);
}
}
这里是我在DatabaseManager类中的isCurrentUserRegistered()方法:
public boolean isCurrentUserRegistered() {
Query query = databaseReference.child("/" + MessageTypes.REGISTER_USER_MESSAGE + "/" + CurrentUser.getInstance().getUserId());
query.addValueEventListener(isUserRegisteredDataListener);
System.out.println("REGISTERED:" + isUserRegisteredDataListener.isUserRegisterd()); //This also prints false no matter what
return isUserRegisteredDataListener.isUserRegisterd();
}
这里是我的IsUserRegisteredDataListener
public class IsUserRegisteredDataListener implements ValueEventListener {
static boolean exists;
private static IsUserRegisteredDataListener isUserRegisteredDataListener;
public IsUserRegisteredDataListener() {
isUserRegisteredDataListener = this;
}
public static IsUserRegisteredDataListener getInstance() {
if (isUserRegisteredDataListener == null) {
isUserRegisteredDataListener = new IsUserRegisteredDataListener();
}
return isUserRegisteredDataListener;
}
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
this.exists = dataSnapshot.exists();
System.out.println("EXISTS" + exists)); //This prints true
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
public boolean isUserRegisterd() {
return exists;
}
我不明白为什么前两种方法打印出FALSE,但是使用实际数据监听器的方法在监听器内部打印出TRUE