问题
I am trying to get Root Node Names if specified myid value is present inside the node.
For Example: Consider following structure
-Likes
-uid1
-postid1
-myid
-othersid1
-othersid2
-postid2
-othersid1
-othersid2
-uid2
-postid3
-myid
-othersid2
I want to get uid1 and postid1 rootnames if myid value is present inside the node. Similarly get uid2 and postid3 rootnames if myid present inside that node.
I have written like this.
public void checkNode()
{
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes");
reference.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds1: dataSnapshot.getChildren())
for(DataSnapshot ds2: ds1.getChildren())
if(ds2.hasChild("myid"))
Log.i("app","present inside: "+ds1.getKey()+" > "+ds2.getKey());
}
public void onCancelled( DatabaseError databaseError) {
}
});
}
This code works correctly. But Is it efficient to use nested for loops? How do i write this code more efficiently if not efficient?
回答1:
To solve your problem use this code
FirebaseDatabase.getInstance().getReference("/Likes/").orderByChild("myid").equalTo("some value").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
/**
* -Likes
* -uid1
* -postid1
* -myid
*/
//You are at myid ref
//get postid reference like below
DatabaseReference postIdRef = dataSnapshot.getRef().getParent();
//uidRef
DatabaseReference uidRef = postIdRef.getParent();
//likesRef
DatabaseReference likesRef = uidRef.getParent();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Once your code hit the code-block of onDataChanged(DataSnapshot snapshot)
You can use snapshot and then call getRef() and then getParent() methods
once you get parent node reference you can use that to traverse in the down tree using getChilderen()
The only thing to keep in mind is that your FirebaseUser should have read permission to this parent node else you will get an exception.
Once your code hit the code-block of onDataChanged(DataSnapshot snapshot)
You can use snapshot and then call getRef() and then getParent() methods
once you get parent node reference you can use that to traverse in the down tree using getChilderen()
The only thing to keep in mind is that your FirebaseUser should have read permission to this parent node else you will get an exception.
来源:https://stackoverflow.com/questions/61981810/how-to-get-nested-root-names-for-present-value-firebase