java – 如何从dataSnapshot获取值?

当我调试此代码时,在databaseUser中dataSnapshot具有来自User in database的值,但是在对象user1中没有添加,它全部为null.我不明白,因为在对象事件中正常接收值.

databaseEvent.child(getKeyEvent()).addListenerForSingleValueEvent( 
      new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

               final Event event = dataSnapshot.getValue(Event.class);
               user = FirebaseAuth.getInstance().getCurrentUser();
               if(user != null) {

                   databaseUser.orderByChild("userEmail").equalTo(user.getEmail()).addListenerForSingleValueEvent(new ValueEventListener() {
                     @Override
                     public void onDataChange(DataSnapshot dataSnapshot) {
                         if (dataSnapshot.exists()) {
                             //User already exists
                             User user1 = dataSnapshot.getValue(User.class);
              }
       }
});

我的数据库用户,仅供测试:

public class User {

String userId;
String userEmail;
Boolean userHasInterest;
String eventId;

public String getUserId() {
    return userId;
}
public String getUserEmail() {
    return userEmail;
}

public Boolean getUserHasInterest() {
    return userHasInterest;
}

public String getEventId() {
    return eventId;
}

public User(String userId, String eventId, String userEmail, Boolean userHasInterest) {
    this.userId = userId;
    this.userEmail = userEmail;
    this.userHasInterest = userHasInterest;
    this.eventId = eventId;
}

而方法,只是为了选择另一个活动的事件的关键:

public String getKeyEvent(){
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String key = bundle.getString("Evento");
    return key;
} 
最佳答案
对Firebase数据库执行查询时,可能会有多个结果.通过附加ValueListener,您可以在一个快照中获得这些结果,因此快照包含这些结果的列表.即使只有一个结果,快照也会包含一个结果的列表.

您的代码未能将此“结果列表”考虑在内.通过循环DataSnapshot.getChildren()很容易解决:

databaseUser.orderByChild("userEmail").equalTo(user.getEmail()).addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
     for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
         User user1 = userSnapshot.getValue(User.class);

转载注明原文:java – 如何从dataSnapshot获取值? - 代码日志