Все уведомления для указанного пользователя c удаляются из базы данных, когда нужно удалить только одно - PullRequest
0 голосов
/ 27 апреля 2020

Проблема, с которой я столкнулся, заключается в том, что я написал два разных метода: 1 для добавления уведомления в базу данных и 1 для удаления этого уведомления. Вы получаете уведомление - другому пользователю нравится ваше сообщение, комментарии к вашему сообщению, нравится ваш комментарий и т. Д. c. В этих случаях пользователь, чья публикация будет отправлена, получит уведомление о том, что вам понравился его комментарий или его сообщение и т. Д. c.

Проблема в том, что уведомления хорошо сохраняются в базе данных, но когда пользователю, например, не нравится сообщение, удаляется не только это уведомление, но и все уведомления этого пользователя. Я не уверен, почему это происходит, я просто хотел бы удалить из базы данных одно уведомление с указанием c notificationId, а не все уведомления, полученные пользователем.

enter image description here

PostAdapter

holder.like.setOnClickListener(v -> {
            if (holder.like.getTag().equals("like")) {
                FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(mFirebaseUser.getUid()).setValue(true);
                addNotification(post.getPublisher(), post.getPostid());
            } else {
                FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(mFirebaseUser.getUid()).removeValue();
                deleteNotification(post.getPublisher());
            }
        });

 private void addNotification(final String userid, final String postid) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);

        String notificationId = reference.push().getKey();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userid", mFirebaseUser.getUid());
        hashMap.put("comment", "liked your event");
        hashMap.put("postid", postid);
        hashMap.put("notificationId", notificationId);
        hashMap.put("ispost", true);

        if (notificationId != null)
            reference.child(notificationId).setValue(hashMap);
    }

    private void deleteNotification(String userid) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Notification notification = snapshot.getValue(Notification.class);
                    if (notification != null) {
                        reference.child(notification.getNotificationId()).removeValue();
                    }
                }
            }

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

            }
        });
    }

Второй метод

holder.like.setOnClickListener(v -> {
        if (holder.like.getTag().equals("like")) {
                FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(mFirebaseUser.getUid()).setValue(true);
                addNotification(post.getPublisher(), post.getPostid());
            } else {
                FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(mFirebaseUser.getUid()).removeValue();
                FirebaseDatabase.getInstance().getReference().child("Notifications").child(post.getPublisher()).child(mNotificationId).removeValue();
            }
        });

private void addNotification(final String userid, final String postid) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);

        mNotificationId = reference.push().getKey();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userid", mFirebaseUser.getUid());
        hashMap.put("comment", "liked your event");
        hashMap.put("postid", postid);
        hashMap.put("notificationId", mNotificationId);
        hashMap.put("ispost", true);

        reference.child(mNotificationId).setValue(hashMap);
    }

1 Ответ

1 голос
/ 28 апреля 2020
if (notification != null) {
     reference.child(notification.getNotificationId()).removeValue();
}

Эти строки должны измениться. Поскольку идентификатор уведомления никогда не равен NULL и все уведомления удаляются.

if (notification.getUserId().equals(mFirebaseUser.getUid())) {
     reference.child(notification.getNotificationId()).removeValue();
}

Или вы можете сохранить идентификатор уведомления другим способом и удалить уведомление без проверки всех уведомлений.

Добавить удовольствие c:

private void addNotification(final String userid, final String postid) 
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);

mNotificationId = reference.push().getKey();

HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", mFirebaseUser.getUid());
hashMap.put("comment", "liked your event");
hashMap.put("postid", postid);
hashMap.put("notificationId", mNotificationId);
hashMap.put("ispost", true);

reference.child(mNotificationId).setValue(hashMap);

HashMap<String, Object> hashMap2 = new HashMap<>();
hashMap2.put("notificationId", mNotificationId);     
hashMap2.put("like", true);
FirebaseDatabase.getInstance().getReference().child("Likes").child(postid).child(mFirebaseUser.getUid()).setValue(hashMap2);
}

удалить удовольствие c:

 private void deleteNotification(String userid, final String postid)) {
 DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(mFirebaseUser.getUid());

 reference.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()){
          String notificationId = dataSnapshot.child("notificationId").getValue(String.class);

          FirebaseDatabase.getInstance().getReference("Notifications")
          .child(userid).child(notificationId).removeValue();
          reference.removeValue();
      }
 }

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

 }
 });
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...