0
{
  "users": {
    "-KKUmYgLYREWCnWeHCvO": {
      "fName": "Peter",
      "ID": "U1EL9SSUQ",
      "username": "peter01"
    },
    "-BBUmYgLYREWCnWPDndk": {
      "fName": "John",
      "ID": "U1EL5623",
      "username": "john.doe"
    }
  }
}

There is a possibility in my code where these 3 fields can get added again, with a different parent id For example, this can get added again, which I want to avoid

 "fName": "Peter",
      "ID": "U1EL9SSUQ",
      "username": "peter01"

So how to check if all 3 fields under a unique parent id already exists?

 mDatabaseUsers.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot data: dataSnapshot.getChildren()){
            if (data.child("fName").exists() && data.child("ID").exists() &&
                    data.child("username").exists()) {
                //do ur stuff


            } else {
                //do something



            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }


});

I tried the above code and it didnt work

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
MrRobot9
  • 2,402
  • 4
  • 31
  • 68

1 Answers1

0

If you have a combination of properties that must be unique, considering using the values of those properties as the key of the nodes. In your sample snippet that would look like:

{
  "users": {
    "U1EL9SSUQ_Peter_peter01": {
      "fName": "Peter",
      "ID": "U1EL9SSUQ",
      "username": "peter01"
    },
    "U1EL5623_John_john,doe": {
      "fName": "John",
      "ID": "U1EL5623",
      "username": "john.doe"
    }
  }
}

If you store the data in this way the combination is guaranteed to be unique, since keys are by definition unique within their parent node.

Note that uniqueness of values has been covered regularly before, so I recommend you check out some of these too:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807