我正在尝试创建一个名为sendRegisterUserMessage()的方法,如果数据库中尚不存在用户,则该方法会将User对象发送到Firebase数据库。出于某种原因,尽管使用侦听器在数据库中找到了对象,但该方法始终返回false。
无论如何我在onCreate()的MainActiviy中调用了这个方法:
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();
}
这是我的IsUerRegisteredDataListener
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
答案 0 :(得分:2)
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();
}
在此方法中,您必须等待firebase结果获得isUserRegistered
。所以你的IsUserRegisteredDataListener
课程无法按你的意愿工作。
您能否显示初始化isUserRegisteredDataListener
字段的位置?