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);
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 05, 2022Comments
-
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.
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 about 6 yearseven if he solves it like you suggest, it will always return an empty list: synchronous call to an asynchronous data fetch
-
balsick about 6 yearsdude, what are you talking about? There is no
filterByKey
, perhaps you meanorderByKey
+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 over 4 yearsWhy to use timeout of 10 sec here. Its bad to slow the server