Home > Software design >  Firebase realtime database how to get a child record without the key
Firebase realtime database how to get a child record without the key

Time:10-07

I have a Firebase database with a "users" node that has some children and I would like to retrieve the "type" field for a specific user, but I don't know what that user's key would be. I have the following data structure:

users
    -MlHrU3_UgMzrU3IpfOW
       email: 
          "[email protected]"
       tipo: 
           "Aluno"

I tried to do it like this but it always returns null

final String[] tipoUserBD = new String[1];
    database = FirebaseDatabase.getInstance().getReference("users");
    database.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            list.clear();
            for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                if(dataSnapshot.child("email").getValue(String.class).equals(user.getEmail())) {
                    tipoUser[0] = dataSnapshot.child("tipo").getValue().toString();
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

CodePudding user response:

If you know the key of the user (I know you don't, but let's assume you do in some other case), you can read their profile and log their type with:

database = FirebaseDatabase.getInstance().getReference("users");
database.child("-MlHrU3_UgMzrU3IpfOW").addValueEventListener(new ValueEventListener() {
         //            
  • Related