Reputation: 1331
I am trying to return the UID key value in Firebase from a search on its child parameters.
-Users
-BCsuC4XAZq0MDK1taLcD2
-Name: Test1
-Phone: 0011223344
-t50GPKxb8mgINGbmGJrR83
-Name: Test2
-Phone: 9988776655
So from this database above, I am trying to implement a search function based on the phone number, where a user searching for "9988776655" will get the return value of "t50GPKxb8mgINGbmGJrR83", but after hours of messing about I am no closer to being able to do this.
There is a post here:
Query Firebase based on field and return parent in Android
That looks like it would be pretty close, but unfortunately the full solution code is not offered. After dabbling around with it, the best I can get trying to fit it into my scenario is a null response.
Does anyone have any idea how I can actually do this? I have read dozens of forum posts, and watched several youtube tutorials but no one seems to be able to do this. Is it possible?
Upvotes: 3
Views: 2983
Reputation: 80914
Try this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Phone").equalTo(9988776655).addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Using the above, you will be on the datasnapshot Users
, then since you want to search based on the phone number, you can do this orderByChild("Phone").equalTo(9988776655)
which will search the phone number that is equal to the value provided. The value can be a variable that you add there or a string "9988776655"
.
Then to be able to get the random id, you need to iterate inside the direct children, using getKey()
you will be able to retrieve the random id of the phone that is equal to 9988776655
Upvotes: 4