Get element by key with Firebase

14,069

The issue is here:

if (item.getKey()==uid)

since you are comparing 2 String in java you have to use the method string.equals(Object other) not the == operator.

Moreover, since you know the key of the data in Firebase you can use it to get the reference without cycling all children.
Something like:

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users").child(uid);
Share:
14,069
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    I've been trying to retrieve an element from my Firebase database using its key. I have a class User and users are present in database.

    1

    I want to retrieve an object user using its key with this method :

    public User getConnectedUserByUId(final String uid){
        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        DatabaseReference ref = database.child("users");
        final List<User> connectedUser= new ArrayList<User>();
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot item: dataSnapshot.getChildren()) {
                    if (item.getKey()==uid)
                    {
                        User user= dataSnapshot.getValue(User.class);
                        connectedUser.add(user);
                    }
    
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
    
        });
        return connectedUser.get(0);
    }
    

    but it returns an empty list every time.

  • balsick
    balsick about 6 years
    even if he solves it like you suggest, it will always return an empty list: synchronous call to an asynchronous data fetch
  • balsick
    balsick about 6 years
    dude, what are you talking about? There is no filterByKey, perhaps you mean orderByKey + equalTo, and this would still be a bad suggestion because it would be a useless overkill. If you have the key, just use it in composing the path
  • Anand_5050
    Anand_5050 over 4 years
    Why to use timeout of 10 sec here. Its bad to slow the server