Recyclerview没有更新?

时间:2017-06-01 12:55:23

标签: java android android-recyclerview

我正在使用聊天应用。在这个应用程序中,我想用最新的消息时间戳对联系人列表进行排序。

     adapter = new ContactListAdapter(ob1, getActivity(), fusername);

            if (!adapted) {
                chatLists.setAdapter(adapter);
                adapted = true;
            }else {
                adapter.updateList(ob1, getActivity(), fusername);

            }

这里setAdapter运行正常,使用setAdapter更新完整的recyclerview也可以正常工作。但它会使用图像和用户消息等所有数据重新加载完整视图。所以我只想刷新索引而不再重新加载所有数据。

关于上面的代码。 adapt是一个布尔值。它的初始值是错误的。设置适配器后初始值更改为true。然后更新适配器我调用updateList函数。

public class ContactListAdapter extends RecyclerView.Adapter<ContactListAdapter.viewHolder>{
    com.google.firebase.database.DataSnapshot d;
    Context c;
    JsonParser parser = new JsonParser();
    String username;
    ArrayList<ChatroomLists> ob1 = new ArrayList<ChatroomLists>();


public ContactListAdapter(ArrayList<ChatroomLists> ob1, Context c, String fusername) {
    this.c = c;
    this.username = fusername;
    this.ob1.addAll(ob1);

}
public void updateList(ArrayList<ChatroomLists> ob1, Context c, String fusername) {
    this.ob1.clear();
    this.ob1.addAll(ob1);
    this.notifyDataSetChanged();


}


    public class viewHolder extends RecyclerView.ViewHolder {
        CircleImageView user_img;
        ImageView message_stats;
        TextView user_name;
        TextView user_message;
        TextView timestamp;
        CircleImageView unreadbadge;

        public viewHolder(View itemView) {
            super(itemView);
            user_img = (CircleImageView) itemView.findViewById (R.id.user_img_list);
            user_name = (TextView) itemView.findViewById (R.id.contact_name);
            user_message = (TextView) itemView.findViewById (R.id.user_message);
            message_stats = (ImageView) itemView.findViewById (R.id.message_status);
            timestamp = (TextView)itemView.findViewById(R.id.time);
            unreadbadge = (CircleImageView) itemView.findViewById(R.id.unread);
        }
    }

    @Override
    public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.chat_list_style, parent, false);

        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(viewHolder holder, int position) {
        ChatroomLists chatroomLists =  ob1.get(position);
        Iterator<ChatroomLists> iter = ob1.iterator();
        String id = chatroomLists.getId();
        String time = chatroomLists.getTimestamp();



        Handler h = new Handler();
        FirebaseDatabase.getInstance().getReference().child("unread").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("chatrooms").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                try{
                    if (dataSnapshot.hasChild(id)){
                        holder.unreadbadge.setVisibility(View.VISIBLE);

                    }else {
                        holder.unreadbadge.setVisibility(View.GONE);

                    }
                }catch (Exception e){

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                try{
                    long mtime = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis())-TimeUnit.MILLISECONDS.toMinutes(Long.parseLong(time));
                    if (mtime<60){
                        holder.timestamp.setText(String.valueOf(mtime)+ " mins");
                        if (mtime==1)
                            holder.timestamp.setText(1+ " min");
                        else if (mtime<1){
                            holder.timestamp.setText("Just Now");

                        }
                        else
                            holder.timestamp.setText(mtime+ " mins");
                    }
                    else if (mtime>60 && mtime<1440){
                        if (mtime/60==1)
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hour");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hours");
                    }
                    else if (mtime>=1440&&mtime<10080){
                        if (mtime/1440==1)
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " day");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " days");
                    }else if(mtime>10080&&mtime<3679200){
                        if (mtime/10080==1)
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " week");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " weeks");

                    }else if(mtime>3679200){
                        if (mtime/3679200==1)
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " year");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " years");
                    }
                }catch (Exception e){

                }

                h.postDelayed(this,60000);
            }
        },60000);

        FirebaseDatabase.getInstance().getReferenceFromUrl("https://droidchatz.firebaseio.com/groupchat/" + id + "/chat").limitToLast(1).addValueEventListener(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
                for (com.google.firebase.database.DataSnapshot d: dataSnapshot.getChildren()){
                    if (dataSnapshot.child(d.getKey()).child("type").getValue(String.class).equals("text"))
                    holder.user_message.setText (dataSnapshot.child(d.getKey()).child("message").getValue(String.class));
                    else if(dataSnapshot.child(d.getKey()).child("type").getValue(String.class).equals("video"))
                        holder.user_message.setText ("New Video Message");

                    else if(dataSnapshot.child(d.getKey()).child("type").getValue(String.class).equals("image"))
                        holder.user_message.setText ("New Image Message");

                    else if(dataSnapshot.child(d.getKey()).child("type").getValue(String.class).equals("gif"))
                        holder.user_message.setText ("New GIF Message");

                    else if(dataSnapshot.child(d.getKey()).child("type").getValue(String.class).equals("file"))
                        holder.user_message.setText ("New Document");

                    else {
                        holder.user_message.setText (dataSnapshot.child(d.getKey()).child("message").getValue(String.class));

                    }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        FirebaseDatabase.getInstance().getReferenceFromUrl("https://droidchatz.firebaseio.com/groups/"+id+"/image").addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
                try{
                    Glide
                            .with(c)
                            .load(dataSnapshot.getValue(String.class))
                            .asBitmap()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)

                            .dontAnimate()
                            .into(new SimpleTarget<Bitmap>() {

                                @Override
                                public void onResourceReady(Bitmap arg0, GlideAnimation<? super Bitmap> arg1) {
                                    holder.user_img.setImageBitmap(arg0);
                                }});



                }catch (Exception e){

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


        holder.user_name.setText (id);

        holder.itemView.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent (c, ChatRoom.class);
                intent.putExtra("username",username);
                intent.putExtra ("group_name", id);

                c.startActivity (intent);
            }
        });

    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return ob1.size();
    }


    }

那么我做错了什么?

2 个答案:

答案 0 :(得分:0)

您只需要为ob1对象添加值,然后致电adapter.notifyDataSetChanged();更新您的列表。

仅初始化适配器一次并填充ob1列表。

答案 1 :(得分:0)

您正在将活动ArrayList引用存储到适配器ArrayList引用中:

  this.ob1 = ob1;

更改适配器构造函数,尝试一次:

 public ContactListAdapter(ArrayList<ChatroomLists> ob1, Context c, String fusername) {
    this.c = c;
    this.username = fusername;
    this.ob1.addAll(ob1);
}