beastlyCoder
beastlyCoder

Reputation: 2401

Count Duplicate Entries Firebase

Here is my Firebase JSON data:

{
  "DjSunGazer" : {
    "-Lm23d6MZV22-yB7TnPr" : {
      "song" : "Ginuwine - So Anxious"
    },
    "-Lm23x2RnlgUJVLW0RFv" : {
      "song" : "Ginuwine - So Anxious"
    }
  }
}

Inside DjSunGazer, instead of adding a totally new song, I want to detect the duplicate and assign it a count of 2. Here is the code I have for adding a new song to my Firebase Database

FirebaseDatabase.getInstance().getReference().addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String s = "";
        String mGroupId = FirebaseDatabase.getInstance().getReference().push().getKey();

        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            s = snapshot.child("song").getValue(String.class);

            Log.d("GET KEY", mGroupId);
        }

        FirebaseDatabase.getInstance().getReference().child(AddSongRequest.getAssociatedAcct).child(mGroupId).child("song").setValue(mSongList.get(vHolder.getAdapterPosition() + 1));
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

How can I prevent it from adding a totally new instance, and instead create another child of the name "count" that will update the values accordingly? I have been struggling with this, thanks in advance!

Upvotes: 0

Views: 266

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

it'll be a lot easier to guarantee uniqueness if you use the thing that needs to be unique as the key of the node. So if the song title needs to be unique, use that as the key. Then use child nodes (for example with push IDs) under there to get the count.

So if you identify a song by its title, and use push IDs to track the requests:

{
  "DjSunGazer" : {
    "Ginuwine - So Anxious": {
      "-Lm23d6MZV22-yB7TnPr" : true,
      "-Lm23x2RnlgUJVLW0RFv" : true
  }
}

To add a request for this song, you'd do:

DatabaseReference root = FirebaseDatabase.getInstance().getReference();
root.child("DjSunGazer/Ginuwine - So Anxious").push(true);

Upvotes: 1

Related Questions