0

Hi searching a lot but cant find any questions who are related with my topic / or was answered.

Im using Firebase Database with these structure (from firebase official documentation)

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

The Docu says: Check if /$uid/groups/$group_id is null

This approach, inverting the data by listing the IDs as keys and setting the value to true, makes checking for a key as simple as reading /users/$uid/groups/$group_id and checking if it is null. The index is faster and a good deal more efficient than querying or scanning the data.

But how can i manage this in Java Code?

With something like this?

mDatabase.child("table/foo").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //

i need a simple true or false after this query

if(query) {
user is in Group
... else {
User is not in group

Just or better highlighting

key is my userID

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference memberDatabaseReference = rootRef.child("groups").child(groupName).child("members").child(key);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (!dataSnapshot.exists()) {
            Log.d("TAG", "Member does not exist!");
        } else {
            Log.d("TAG", "Member exists!");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
memberDatabaseReference.addListenerForSingleValueEvent(valueEventListener);
KENdi
  • 7,576
  • 2
  • 16
  • 31
thefab
  • 59
  • 1
  • 11

2 Answers2

2

You need to use exists() method on the dataSnapshot object. So, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference memberDatabaseReference = rootRef.child("groups").child(groupName).child("members").child(memberName);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (!dataSnapshot.exists()) {
            Log.d("TAG", "Member does not exist!");
        } else {
            Log.d("TAG", "Member exists!");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
memberDatabaseReference.addListenerForSingleValueEvent(valueEventListener);

In which mamberName is the name of member you want to verify. In this way you can verify the existens of a memeber.

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • My DB Layout is: Benutzer/$UID/groups/admins(which true or false) and in my Groups /groups/admins/members/usernames = true so in your Code i have to use this? [..] = rootRef.child("groups").child("admins").child("members").child("USERID").child(memberName); what is the memberName? oh okay, i think MemberName is my userID i will give it a try – thefab Jun 28 '17 at 16:24
  • Yes, you need to go down in the tree to reach the group node, where you need to do the verification. So if those are the correct childs, yes, give it a try. `memberName` is the name of memeber you want to verify. – Alex Mamo Jun 28 '17 at 16:27
  • Okay it works big thanks! Another Question: is this a "fast" solution? In my finally App i have to check this status for about 100 childs (users) i want to display all Childs on a map which are members of my bike group (Users with bike show this map, users with car show an other map) so my query checks 100+ users, but it works and now i unterstand this .exist() method Thank you =) – thefab Jun 28 '17 at 16:34
  • Good to hear that. It's a good solution becase you are checking the members for a specific group. If you want to learn something more complex, i recomand you take a look at this post, [Structuring your Firebase Data correctly for a Complex App](https://www.airpair.com/firebase/posts/structuring-your-firebase-data). – Alex Mamo Jun 28 '17 at 16:41
  • @AlexMamo – Alex, so you're downloading every group data and check if the user uid appears in the group members? – Cesare Jul 14 '17 at 09:34
  • 1
    As you see in `memberDatabaseReference`, we are downloading only a particular group, note the entire node (not every group). – Alex Mamo Jul 14 '17 at 09:40
  • @AlexMamo – hold on, so the best practice to fetch groups given the user uid is to first get user groups (`user/$user_uid/groups/`) and then fetch the group data given the groups I've just fetched? Thank you! – Cesare Jul 14 '17 at 10:51
  • Depends on what you really want to achieve. All the groups in which the users belongs, or all the users who are apart of a single group. In both cases, you need to do in the way you say. – Alex Mamo Jul 14 '17 at 10:56
0

Make a node in your firebase security like this

{
    "rules":{
    "checkIfMemberIsInGroup":{
        "$groupId":{
            "$memberId":{
                ".read":false,
                ".write":"auth != null && !newData.exists() &&
                 root.child('groups').child($groupId).child('members').child($memberId).exists()"
            } 
        }
    }
}

Then check if user is part of group with lightweight query, and let server takeup bandwidth..

   FirebaseDatabase.getInstance().getReference().child("checkIfMemberIsInGroup")
            .child(groupName)
            .child(memberName)
            .setValue(null, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (databaseError != null && databaseError.getCode() == DatabaseError.PERMISSION_DENIED) {
                        // user is not member of group
                    } else {
                        // user is member of group
                    }
                }
            });