Firebase database value keeps changing instead of adding itself

What I want to do is to first check whether there's a value in my Firebase database, if there isn't then add it. My database looks like this:

appnickname{
Strings{
    key : value
    key : value
    key : value

And my current code is this:

refference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot n : dataSnapshot.getChildren()) {
                if (n.getValue().equals(string)) {
                    break;
                }
                refference.child("key").setValue(string);
            }
        }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});

The problem with my current code is that it simply changes the string that exists under the same key instead of adding a new key/value combo. The good thing is that if it’s the same value, nothing happens as far as I can see. How can I fix the bad thing?

#java #firebase #loops

8 Likes3.25 GEEK