wejdan
wejdan

Reputation: 47

How to delete a certain data in the Firebase Database?

I'm developing a social networking app, where users can follow other users and like their posts, comments ... Whenever some user follows someone, it shows in a notification fragment in the other user account to inform him that he has a new follower. The problem is that I couldn't remove the notification when the user hits unfollow. Here is what I have tried:

 if ( holder.btn_follow.getText().toString().equals("follow"))
 {
addNotifications(user.getId());
}
 else{
 FirebaseDatabase.getInstance().getReference("Notifications").child(user.getId()).removeValue();
   }

and here is how I added notification:

 private void addNotifications(String userid)
    {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userid", firebaseUser.getUid());
        hashMap.put("text"," started following you");
        hashMap.put("postid","");
        hashMap.put("ispost",false);
        reference.push().setValue(hashMap);
    }

the problem with my code is that whenever the user unfollows someone, all the notifications from that user are deleted including his likes and comments. all I want is to delete "started following you". Here is how it looks in the Firebase database.

enter image description here

Upvotes: 0

Views: 523

Answers (1)

Mostafa Soliman
Mostafa Soliman

Reputation: 872

Use Firebase Query refers to Firebase Docs, it will be something like this

Query queryRef = mReference.child("Notifications").child(userId).orderByChild("text").equalTo("start following you");

queryRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot snapshot, String previousChild) {
      // snapshot.getRef().setValue(null);
      snapshot.getRef().remove();
    }
});

Upvotes: 1

Related Questions