创建新的子级后,Recyclerview会不断从Firebase DB重新填充数据

时间:2018-08-23 19:19:10

标签: android firebase android-fragments firebase-realtime-database android-recyclerview

我目前正在处理聊天应用程序,遇到了一个问题。我的Chat Fragment包含我的Recyclerview,该数据来自Firebase DB。我可以获取数据,但是遇到了问题。当我打开Chat Activity并发送消息时,将使用存储在子级中的信息创建一个新的push id。我的recyclerview获得的数据是它获取最后的push id并检索了最后发送的消息。问题是,当我回到自己的fragment时,recyclerview会重新填充并添加创建的新push id最后一条消息,并创建另一个项目,而不仅仅是刷新原始项目。

因此,从本质上讲,我将加载我的应用程序,进入Chat Fragment,我的recyclerview将显示另一个用户和最后发送的消息,没问题,然后单击该项目,打开chat activity,发送消息,然后返回。现在,当我回到chat fragment时,将在recyclerview中显示两三个或许多已发送的消息。不确定如何解决此问题,我的代码如下:

数据库结构 Database Structure

  

聊天片段

public class Fragment_MatchChats extends Fragment {
private RecyclerView mRecyclerView, mRecyclerViewChat;
private RecyclerView.Adapter mMatchesAdapter, mChatAdapter;
private String currentUserID;
private DatabaseReference mDatabaseChat;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag_match_chat, container, false);


currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
LinearLayoutManager layoutManagerChat = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerViewChat = (RecyclerView) v.findViewById(R.id.recyclerViewChat);
mRecyclerViewChat.setHasFixedSize(true);
mRecyclerViewChat.setLayoutManager(layoutManagerChat);

mChatAdapter = new RecyclerViewChatAdapter(getDataSetChat(), getContext());

getUserMatchId();
return v;
}


//this method will get the user ID in the database that you matched with. It will run through the matches child and get all the user IDs
private void getUserMatchId() {
    DatabaseReference matchDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches");
    matchDB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for(DataSnapshot match : dataSnapshot.getChildren()){
                    CheckChatID(match.getKey());
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void CheckChatID(final String chat) {
    DatabaseReference ChatDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches")
            .child(chat).child("ChatID");
    ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                String ChatID = dataSnapshot.getValue().toString();
                ChatIDExist(ChatID, chat);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void ChatIDExist(final String chatID, final String oppUserID) {
    final DatabaseReference ChatDB = mDatabaseChat.child(chatID);
    final Query lastQuery = ChatDB.orderByKey().limitToLast(1);
    ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
              lastQuery.addValueEventListener(new ValueEventListener() {
                   @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {
                       for(DataSnapshot child: dataSnapshot.getChildren()){
                           String key = child.child("text").getValue().toString();
                           FetchChatInfo(oppUserID,key);

                       }
                   }

                   @Override
                   public void onCancelled(DatabaseError databaseError) {

                   }
               });
            } 
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void FetchChatInfo(String key, final String chatID) {
    DatabaseReference userDB = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
    userDB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                String matched_userID = dataSnapshot.getKey();
                String matches_userName = "";
                String matches_userProPic = "";
                String match_CHATID = chatID;

                if(dataSnapshot.child("name").getValue() != null){
                    matches_userName = dataSnapshot.child("name").getValue().toString();
                }
                if(dataSnapshot.child("profilePicURL").getValue() != null){
                    matches_userProPic = dataSnapshot.child("profilePicURL").getValue().toString();
                }


                RecyclerViewChatReference chat_obj = new RecyclerViewChatReference(matched_userID, matches_userName, matches_userProPic, match_CHATID);
                resultsChats.add(chat_obj);
                mRecyclerViewChat.setAdapter(mChatAdapter);
                mChatAdapter.notifyDataSetChanged();

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private ArrayList<RecyclerViewChatReference> resultsChats = new ArrayList<RecyclerViewChatReference>();

private List<RecyclerViewChatReference> getDataSetChat() {
    return resultsChats;
}
  

聊天活动

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    matchId = getIntent().getExtras().getString("matchID");

    currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();

    mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID)
            .child("swipes").child("matches").child(matchId).child("ChatID");
    mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");

    getChatId();

    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    mRecyclerView.setNestedScrollingEnabled(false);
    mRecyclerView.setHasFixedSize(false);
    mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
    mRecyclerView.setLayoutManager(mChatLayoutManager);
    mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
    mRecyclerView.setAdapter(mChatAdapter);

    mSendEditText = findViewById(R.id.message);
    mSendButton = findViewById(R.id.send);

    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });


}

private void sendMessage() {
    String sendMessageText = mSendEditText.getText().toString();

    if(!sendMessageText.isEmpty()){
        DatabaseReference newMessageDb = mDatabaseChat.push();

        Map newMessage = new HashMap();
        newMessage.put("createdByUser", currentUserID);
        newMessage.put("text", sendMessageText);

        newMessageDb.setValue(newMessage);
    }
    mSendEditText.setText(null);
}

private void getChatId(){
    mDatabaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                chatId = dataSnapshot.getValue().toString();
                mDatabaseChat = mDatabaseChat.child(chatId);
                getChatMessages();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void getChatMessages() {
    mDatabaseChat.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if(dataSnapshot.exists()){
                String message = "";
                String createdByUser = "";

                if(dataSnapshot.child("text").getValue()!=null){
                    message = dataSnapshot.child("text").getValue().toString();
                }
                if(dataSnapshot.child("createdByUser").getValue()!=null){
                    createdByUser = dataSnapshot.child("createdByUser").getValue().toString();
                }

                if(message!=null && createdByUser!=null){
                    Boolean currentUserBoolean = false;
                    if(createdByUser.equals(currentUserID)){
                        currentUserBoolean = true;
                    }
                    ChatObject newMessage = new ChatObject(message, currentUserBoolean);
                    resultsChat.add(newMessage);
                    mChatAdapter.notifyDataSetChanged();
                }
            }

        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}


private ArrayList<ChatObject> resultsChat = new ArrayList<ChatObject>();
private List<ChatObject> getDataSetChat() {
    return resultsChat;
}
} 

0 个答案:

没有答案