Firebase RecyclerView OnDataChanged仅显示最后一个元素 [英] Firebase RecyclerView OnDataChanged only last element is Shown
问题描述
我正在按照请帮助,不要拒绝我的问题感谢您的帮助
之所以会发生这种情况,是因为调用 onBindViewHolder()
方法的次数与来自数据库的项目数一样多.因此,在这种情况下,此方法内部的所有内容也会被触发.这意味着您将在每个 onBindViewHolder()
方法调用上附加一个侦听器.不需要这样做.您可以直接从 model
对象直接获取用户名和所有其他属性,该对象作为参数传递给此方法,如下所示:
String UserName = model.getUserName();字符串UserStatus = model.getUserStatus();//对于其他属性,依此类推.
I am developing android chat app following this i am retriving the whole list of friends Then on the basis of their user id i retrive the user's data from the user data that is user name, user image and user status the databases are shown below.
and
So now what is the main problem, the main problem is by the following code:
@Override
protected void onBindViewHolder(FriendsFragment.friendsViewHolder holder, int position, Friends model) {
final String list_User_id=getRef(position).getKey();
mUserdatabase.child(list_User_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserName = dataSnapshot.child("name").getValue().toString();
friendsViewHolder.setName(UserName);
UserStatus = dataSnapshot.child("status").getValue().toString();
friendsViewHolder.setStatus(UserStatus);
thumb_img = dataSnapshot.child("thumb_img").getValue().toString();
friendsViewHolder.setThumbnail(thumb_img,getActivity());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent prfile_Intent=new Intent(getActivity(),ProfileActivity.class);
prfile_Intent.putExtra("User_id",list_User_id);
startActivity(prfile_Intent);
}
});
it give me a recyclerView in result in which only last element is show as shown in figure
i google it and also searching on Stackover flow but cannot find the solution from last 3 days. A simillar is Question is asked but i cannot solve my problem from here please help and donot down vote my question thanks for help
This is happening because the onBindViewHolder()
method is called as many times as the number of items that are coming from your database. So in this case, everything is inside this method is also triggered. This means that you are attaching a listener on every onBindViewHolder()
method call. There is no need for doing that. You can simply get the user name and all the other properties directly from the model
object which is passed as an argument to this method like this:
String UserName = model.getUserName();
String UserStatus = model.getUserStatus();
//And so on for the other properties.
这篇关于Firebase RecyclerView OnDataChanged仅显示最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!