0

I have a app chat based on firebase database and I want to know if a particular value is already stored.

Database structure

According to the above structure how can I prevent two equal values ​​(in red) from being inserted into the same child (blue)?

EDIT

I solved this problem as follows: 1) I changed the push values ​​of each node by unique username; 2) I checked the duplicate values ​​with the code below:

FirebaseDatabase.getInstance().getReference().child("friend").child(value_in_blue)
        .addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(!dataSnapshot.hasChild(username)) {
                    //value does not exists
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

Thank you Frank van Puffelen and Jins Lukose for giving me guidance on this issue.

afazolo
  • 382
  • 2
  • 6
  • 22
  • There is no atomic way to prevent duplicate **values** in a tree. The solution is typically to have an additional data structure where the values are used as the keys, because the child keys in a node are by definition guaranteed to be unique. See https://stackoverflow.com/q/39912201, https://stackoverflow.com/a/25328654, https://stackoverflow.com/a/20291163, https://stackoverflow.com/a/35244705 – Frank van Puffelen Nov 13 '18 at 14:48

2 Answers2

2

Firebase provides hasChild() method to check value for child exist or not for pirticuler child. You can refer link for more details

1

Try this

fdbRefer.child("give your value").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exist() {
//comes here if exit
}
else {
//if not exist
}
}
});
Jins Lukose
  • 699
  • 6
  • 19