根据最新消息对回收者视图项目进行排序

时间:2019-07-18 13:24:16

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

我正在使用Firebase构建聊天应用程序,我想根据最新消息对聊天列表进行排序。您上次向其发送消息的用户应该出现在顶部。以前的消息应该在下面,请帮助!

我已经尝试过orderbychild(“ time”)无效。

enter image description here

聊天片段

public class ChatsFragment extends Fragment {
    private View PrivateChatView;
    private RecyclerView chatsList;
    private RecyclerView chatsLists;

    private DatabaseReference ChatsRef,
    UsersRef,
    RootRef,
    MsgRef;
    private FirebaseAuth mAuth;
    private FirebaseUser mUser;
    private String currentUserID;
    private String theLastMessage;

    public ChatsFragment() { // Required empty public constructor
    }

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment
        PrivateChatView = inflater.inflate(R.layout.fragment_chats, container, false);
        mAuth = FirebaseAuth.getInstance();
        mUser = FirebaseAuth.getInstance().getCurrentUser();
        currentUserID = mAuth.getCurrentUser().getUid();
        ChatsRef = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUserID);
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
        MsgRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
        RootRef = FirebaseDatabase.getInstance().getReference();

        chatsList = (RecyclerView)PrivateChatView.findViewById(R.id.chats_list);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        chatsList.setLayoutManager(layoutManager);

        chatsLists = (RecyclerView)PrivateChatView.findViewById(R.id.chats_lists);
        chatsLists.setLayoutManager(new LinearLayoutManager(getContext()));

        updateToken(FirebaseInstanceId.getInstance().getToken());
        return PrivateChatView;
    }

    private void updateToken(String token) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
        Token token1 = new Token(token);
        reference.child(currentUserID).setValue(token1);
    }

    @Override public void onStart() {
        super.onStart();
        chats();
        friends();
    }

    private void chats() {
        FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(MsgRef.getRef().orderByChild("date"), Friends.class).build();

        FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
            @Override protected void onBindViewHolder(@NonNull final ChatsViewHolder holder, int position, @NonNull final Friends model) {

                final String usersID = getRef(position).getKey();
                final String[] retImage = {
                    "default_image"
                };

                final String list_user_id = getRef(position).getKey();

                Query lastMessageQuery = MsgRef.child(list_user_id).limitToLast(1);

                lastMessageQuery.addChildEventListener(new ChildEventListener() {
                    @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        String data = dataSnapshot.child("time").getValue().toString();
                        String data1 = dataSnapshot.child("date").getValue().toString();
                        holder.userStatus.setText(data + " " + data1);
                        holder.userStatus.setTypeface(null, Typeface.NORMAL);
                    }

                    @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) {}
                });


                UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
                    @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.hasChild("image")) {
                            retImage[0] = dataSnapshot.child("image").getValue().toString();
                            Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
                        }

                        final String retName = dataSnapshot.child("name").getValue().toString();
                        final String retStatus = dataSnapshot.child("status").getValue().toString();
                        holder.userName.setText(retName);

                        if (dataSnapshot.child("userState").hasChild("state")) {
                            String state = dataSnapshot.child("userState").child("state").getValue().toString();
                            String date = dataSnapshot.child("userState").child("date").getValue().toString();
                            String time = dataSnapshot.child("userState").child("time").getValue().toString();
                        }

                        holder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
                                chatIntent.putExtra("visit_user_id", usersID);
                                chatIntent.putExtra("visit_user_name", retName);
                                chatIntent.putExtra("visit_image", retImage);
                                startActivity(chatIntent);
                            }
                        });
                    }

                    @Override public void onCancelled(@NonNull DatabaseError databaseError) {}
                });
            }

            @NonNull @Override public ChatsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
                return new ChatsViewHolder(view);
            }
        };
        chatsList.setAdapter(adapter);
        adapter.startListening();
    }

    private void friends() {
        FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(ChatsRef, Friends.class).build();

        FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
            @Override protected void onBindViewHolder(@NonNull final ChatsViewHolder holder, int position, @NonNull final Friends model) {

                final String usersID = getRef(position).getKey();
                final String[] retImage = {
                    "default_image"
                };

                final String list_user_id = getRef(position).getKey();

                UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
                    @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.hasChild("image")) {
                            retImage[0] = dataSnapshot.child("image").getValue().toString();
                            Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
                        }

                        final String retName = dataSnapshot.child("name").getValue().toString();
                        final String retStatus = dataSnapshot.child("status").getValue().toString();
                        holder.userName.setText(retName);

                        if (dataSnapshot.child("userState").hasChild("state")) {
                            String state = dataSnapshot.child("userState").child("state").getValue().toString();
                            String date = dataSnapshot.child("userState").child("date").getValue().toString();
                            String time = dataSnapshot.child("userState").child("time").getValue().toString();
                        }

                        holder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
                                chatIntent.putExtra("visit_user_id", usersID);
                                chatIntent.putExtra("visit_user_name", retName);
                                chatIntent.putExtra("visit_image", retImage);
                                startActivity(chatIntent);
                            }
                        });
                    }
                    @Override public void onCancelled(@NonNull DatabaseError databaseError) {}
                });
            }

            @NonNull @Override public ChatsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
                return new ChatsViewHolder(view);
            }
        };
        chatsLists.setAdapter(adapter);
        adapter.startListening();

    }

    public static class ChatsViewHolder extends RecyclerView.ViewHolder {
        CircleImageView profileImage;
        TextView userStatus,
        userName;
        ImageView icon;

        public ChatsViewHolder(@NonNull View itemView) {
            super(itemView);

            profileImage = itemView.findViewById(R.id.users_profile_image);
            userStatus = itemView.findViewById(R.id.user_status);
            userName = itemView.findViewById(R.id.user_profile_name);
            icon = itemView.findViewById(R.id.user_online_status);
        }
    }

}

0 个答案:

没有答案