Fabio Nobre Fabio Nobre - 2 months ago 22
Android Question

When I search with child is null in Firebase android?

I have this code:

String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
myRef = database.getReference("reserva/");
myRef.orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

String value = dataSnapshot.child("reserva/1/status").getValue(String.class);
String status;
TextView textview2 = (TextView) findViewById(R.id.TextView2);
if (value != null) {
status = dataSnapshot.getKey() + getString(R.string.statusreservafeita);
textview2.setText(status + value);
} else
textview2.setText(R.string.statusreservafail );
}

@Override
public void onCancelled(DatabaseError error) {
TextView textview2 = (TextView) findViewById(R.id.TextView2);
textview2.setText(R.string.statusreservafail );
}
});


My data :

"reserva" : {
"1" : {
"email" : "teste@teste.com",
"status" : "check in"
},
"2" : {
"email" : "fabio@ciaf.com.br",
"status" : "check out"
},
"123" : {
"email" : "fbaoo07@gmail.com",
"status" : "reservado"
}
}


When I put an email teste@teste.com it returns null. I need it to return the status, but it returns null. I think I am missing a child.

Answer

You have a few problems in your code, but nothing major.

Here's the snippet that will most likely work:

myRef.orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            String status = childSnapshot.child("status").getValue(String.class);
        }
    }

The changes I made are:

  1. I added a loop over dataSnapshot.getChildren(). A query can return multiple children. For that reason it returns a list, even when there is only one match. By looping over dataSnapshot.getChildren() we get each match.
  2. I get the value directly from the statusSnapshot instead of looking it up from the root.

Alternative, if you want to look up the child by its absolute path, you can do something like this:

statusRef = database.getReference("reserva/1/status");
statusRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String status = dataSnapshot.getValue(String.class);
    }
    ... 
Comments