Recyclerview keeps re-populating data from Firebase DB when new child is created

Recyclerview keeps re-populating data from Firebase DB when new child is created



I am currently working on a chat application and have come across an issue. My Chat Fragment contains my Recyclerview which populates data from Firebase DB. I am able to obtain the data, but I am running into an issue. When I open my Chat Activity and send a message, a new push id is created with the information stored in the child. The data obtained by my recyclerview is it gets the last push id and retrieves the last message that was sent. The problem is, when I go back into my fragment, the recyclerview re-populates and adds the new push id last message that was created, and creates another item instead of just refreshing the original item.


Chat Fragment


Recyclerview


Firebase DB


Chat Activity


push id


recyclerview


push id


fragment


push id



So essentially, I will load my app, go into the Chat Fragment, my recyclerview will display the other user and the last message that was sent, no problem, then I will click on that item, open the chat activity, send a message then go back. Now when I am back into the chat fragment I will have two or three or however many messages that were sent displaying in the recyclerview. Not sure on how to fix this, my code is below:


Chat Fragment


recyclerview


chat activity


chat fragment


recyclerview



DATABASE STRUCTURE
Database Structure



Chat Fragment


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;



Chat Activity


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;

}





try to understand i will give u the answer coz i have faced it alot.
– vaibhav sharma
Aug 23 at 19:51





first of all do one thing try using this method "getUserMatchId();" under the onstart method of the fragment
– vaibhav sharma
Aug 23 at 19:59





then do one thing try to determine which thing is already populated in the recycler view by using "contains" method of array list and restrict this to add populate it again in the recycler view
– vaibhav sharma
Aug 23 at 20:02





@vaibhav I tried the putting it into on start it didn't work, it would add two more items instead of one. The second part you said to do I'm not sure how to do that
– BroadwayMayField
Aug 23 at 22:15





When I close the app and open it again it will be fine. Do you think it would work or be easier if I just destroy/detach the chat fragment only when I click on my recyclerview and then when I back press on my chat activity it will re-retach it?
– BroadwayMayField
Aug 23 at 22:26









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)