嘿,我正在创建一个聊天应用,检索消息时出现问题

时间:2020-09-04 09:30:31

标签: android firebase-realtime-database chat

嘿,我正在创建一个聊天应用程序,并将消息存储在firebase数据库中,并且类似地从中检索消息。我的问题是在检索消息时。

为此,我使用了增值事件监听器。我所做的是:

  1. 我将位置放在数据更改上
  2. 我将消息添加到我已连接到回收站视图的arraylist
  3. 在向回收者视图显示文本之后,我已经从该位置本身删除了消息

但是在所有这些之前,我已经在ondata更改内添加了if语句,条件是if(datasnapshot值不为空),然后执行上述3个步骤。令人惊讶地有效。

但是唯一的问题是,每当我退出他/她的聊天活动并与其他人聊天并回到他身边时,我都会收到两次显示他新发送的消息,而当我再次回来时我得到他新发送的消息三次显示,所以我事先不知道该怎么办...

我的代码


myfirebase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                mychildtext=dataSnapshot.getValue(String.class);
                if (!mychildtext.isEmpty())
                {
                    model d=new model();
                    //Here model is model class "List<model> modelList=new Arraylist()"
                    d.setTextMessage(mychildtext);
                    d.setIsme(false);
                    database.maindao().insert(d);
                    //I use database(RoomDB) and add all those stuff to it
                    modelList.clear();
                    modelList.addAll(database.maindao().getAll());
                    recyclerView.smoothScrollToPosition(modelList.size());
                    customAdapter.notifyDataSetChanged();
                    ref.child(temp).setValue("");
                    modelList.clear();
                    //above is the location of the message and so i clear it
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });

my source code

my output

my output

1 个答案:

答案 0 :(得分:0)

得到重复的原因是因为适配器具有在第一个事件侦听器上获取的先前内容。因此,当它再次触发时,它也会获取之前的所有数据。

手动处理事件侦听器非常麻烦。我能做的是向您推荐一个名为FirebaseUI的出色库。它将为您处理进行邮件绑定所需的一些小细节。

https://github.com/firebase/FirebaseUI-Android

它将处理更新持有人。

如果要处理事件侦听器,则可以使用DiffUtil,它可以帮助您将数据绑定到适配器并解决重复消息的问题。