【问题标题】:Data duplicate in listview while fetching from firebase android studio从firebase android studio获取时列表视图中的数据重复
【发布时间】:2019-10-01 10:03:05
【问题描述】:

当我在 listview 中从 firebase 获取数据时,数据会重复自身如何停止重复,请任何人帮助我...

databaseReference.child("Conversation")
    .child(current_token)
    .child(user_token)
    .addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String msgs = null;
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
          ChatMessage chatmessages = snapshot.getValue(ChatMessage.class);
          msgs = chatmessages.getMessageText();
          Log.e("chk", "" + msgs);
          arrayList.add(new chatmessages(msgs)); //here is duplication
        }

        chat = new Chat(getApplicationContext(), arrayList);
        chatlistView.setAdapter(chat);
      }

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

      }
    });
}

【问题讨论】:

标签: android firebase firebase-realtime-database


【解决方案1】:

在从firebase添加新列表或再次初始化列表之前清除arraylist,即

arraylist = new ArrayList();

【讨论】:

    【解决方案2】:

    您在类中创建了arrayList,而不是onDataChange 方法。

    因此,数据列表随着重复数据而增长。 你可以关注

    1) 在onDataChange 中声明arrayList

    2) 在 foreach 之前调用 arrayList.clear()。在这种情况下,您应该改为

    chat = new Chat(getApplicationContext(), arrayList);
    chatlistView.setAdapter(chat);
    

    打电话

    chatlistView.notifyDatasetChanged();
    

    并预先初始化它

    【讨论】:

      【解决方案3】:

      覆盖聊天消息类中的 hashCode() 和 equals() 方法,以便每个聊天消息都是唯一的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-16
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-01
        • 1970-01-01
        相关资源
        最近更新 更多