Java – How do I get values from dataSnapshot?

How do I get values from dataSnapshot?… here is a solution to the problem.

How do I get values from dataSnapshot?

When I debug this code, there is the value of User in the database in the databaseUser dataSnapshot, but in the object user1, it is not added, it is all empty. And I don’t understand because values are received normally in object events.

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);
              }
       }
});

My database user, just test for now:

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;
}

and method, which simply selects the key for another activity’s event:

public String getKeyEvent(){
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String key = bundle.getString("Evento");
    return key;
} 

Solution

When you execute a query against a Firebase database, there may be multiple results. By attaching a ValueListener, you can get these results in a snapshot, so the snapshot contains a list of these results. Even if there is only one result, the snapshot contains a list of results.

Your code does not take this “list of results” into account. It’s easy to fix by iterating through 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);

Related Problems and Solutions