Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element by key with Firebase

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.

like image 668
RadHisoka Avatar asked Mar 07 '17 13:03

RadHisoka


1 Answers

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);
like image 191
Gabriele Mariotti Avatar answered Sep 27 '22 18:09

Gabriele Mariotti