我想获取我在recyclerview中选择的用户ID列表,以便将其添加到群聊中

时间:2019-01-27 00:50:30

标签: android firebase firebase-realtime-database

我正在创建一个类似于whatsapp的聊天应用程序,并且在用户创建组的部分中,我想添加我从列表中选择的所有用户,换句话说,并返回其ID,以便他们可以一起存储在Firebase,以便在该特定组中发送的邮件将到达该组中的每个用户。但是迷路了。下面是我的recyclerView中的代码:

public class RecyclerViewAdapterAddUsers extends RecyclerView.Adapter<RecyclerViewAdapterAddUsers.ViewHolder> {

    Admin admin;

    // variable to store admin uid from sharePreference
    //String admin_uid;

    private Context mCtx;
    private List<Users> mUsers;
    private boolean isChat;

    // string variable to contain lastMessage from user
    private String theLastMessage;

    public RecyclerViewAdapterAddUsers(Context mCtx, List<Users> mUsers, boolean isChat){
        this.mCtx = mCtx;
        this.mUsers = mUsers;
        this.isChat = isChat;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_add_users,parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        // gets the positions of the all users
        final Users users = mUsers.get(position);

        // sets username to the text of the textView
        holder.username.setText(users.getUsername());

        if(users.getImageUrl() == null){
            // loads the default placeholder into ImageView if ImageUrl is null
            holder.profile_pic.setImageResource(R.drawable.ic_person_unknown);
        }
        else{
            // loads users image into the ImageView
            Glide.with(mCtx).load(users.getImageUrl()).into(holder.profile_pic);
        }


        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checks if check box is checked
                if(holder.checkBox.isChecked()){
                    Toast.makeText(mCtx, "User is checked", Toast.LENGTH_SHORT).show();
                }
                else{

                }
            }
        });

    }


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

    public static class ViewHolder extends RecyclerView.ViewHolder{

        Admin admin;

        CircleImageView profile_pic;
        TextView username;
        TextView last_msg;
        CheckBox checkBox;

        // status online or offline indicators
        CircleImageView status_online;
        CircleImageView status_offline;

        public ViewHolder(View itemView) {
            super(itemView);

            profile_pic = itemView.findViewById(R.id.profile_image);
            username = itemView.findViewById(R.id.username);
            checkBox = itemView.findViewById(R.id.add_user);
            status_online = itemView.findViewById(R.id.status_online);
            status_offline = itemView.findViewById(R.id.status_offline);
            last_msg = itemView.findViewById(R.id.last_msg);
        }
    }

    // checks for last message
    private void lastMessage(final String user_id, final TextView last_msg){

        theLastMessage = "default";

        // getting the uid of the admin stored in shared preference
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mCtx);
        final String admin_uid = preferences.getString("uid","");

        DatabaseReference lastMsgRef = FirebaseDatabase.getInstance().getReference("Chats");
        lastMsgRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Chats chats = snapshot.getValue(Chats.class);

                    assert chats != null;

                    // compares the uid of the admin and user and return the last message
                    if(chats.getReceiver().equals(admin_uid) && chats.getSender().equals(user_id)
                            || chats.getReceiver().equals(user_id) && chats.getSender().equals(admin_uid)){
                        theLastMessage = chats.getMessage();
                    }

                }

                // switch case for theLastMessage
                switch (theLastMessage){
                    case "default":
                        last_msg.setText(R.string.no_message);
                        break;

                        default:
                            last_msg.setText(theLastMessage);
                            break;
                }

                theLastMessage = "default";
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // display error message if one should occur
                Toast.makeText(mCtx, databaseError.getMessage(),Toast.LENGTH_LONG).show();
            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

我在需要更改代码的地方放了一个箭头(例如<----)

public class RecyclerViewAdapterAddUsers extends RecyclerView.Adapter<RecyclerViewAdapterAddUsers.ViewHolder> {

Admin admin;

// variable to store admin uid from sharePreference
//String admin_uid;

private Context mCtx;
private List<Users> mUsers;
private boolean isChat;

// string variable to contain lastMessage from user
private String theLastMessage;

// strings to store the ids of chat users <--------------------------------------------
private List<String> selectedUsersIds;
//getter method
List<String> getUserIdsList(){
    return selectedUsersIds;
}

public RecyclerViewAdapterAddUsers(Context mCtx, List<Users> mUsers, boolean isChat){
    this.mCtx = mCtx;
    this.mUsers = mUsers;
    this.isChat = isChat;
    selectedUsersIds = new ArrayList<String>(); // <--------------------------------------------
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerview_add_users,parent, false);

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

    // gets the positions of the all users
    final Users users = mUsers.get(position);

    // sets username to the text of the textView
    holder.username.setText(users.getUsername());

    if(users.getImageUrl() == null){
        // loads the default placeholder into ImageView if ImageUrl is null
        holder.profile_pic.setImageResource(R.drawable.ic_person_unknown);
    }
    else{
        // loads users image into the ImageView
        Glide.with(mCtx).load(users.getImageUrl()).into(holder.profile_pic);
    }


    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // checks if check box is checked
            if(holder.checkBox.isChecked()){
                Toast.makeText(mCtx, "User is checked", Toast.LENGTH_SHORT).show();

                //add the user id to the list <--------------------------------------------
                selectedUsersIds.add(users.getId()); // or whatever the method to get the user id name have <--------------------------------------------
            }
            else{
                //remove the id if the user it's unchecked <--------------------------------------------
                selectedUsersIds.remove(users.getId()); // <--------------------------------------------
            }
        }
    });

}


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

public static class ViewHolder extends RecyclerView.ViewHolder{

    Admin admin;

    CircleImageView profile_pic;
    TextView username;
    TextView last_msg;
    CheckBox checkBox;

    // status online or offline indicators
    CircleImageView status_online;
    CircleImageView status_offline;

    public ViewHolder(View itemView) {
        super(itemView);

        profile_pic = itemView.findViewById(R.id.profile_image);
        username = itemView.findViewById(R.id.username);
        checkBox = itemView.findViewById(R.id.add_user);
        status_online = itemView.findViewById(R.id.status_online);
        status_offline = itemView.findViewById(R.id.status_offline);
        last_msg = itemView.findViewById(R.id.last_msg);
    }
}

// checks for last message
private void lastMessage(final String user_id, final TextView last_msg){

    theLastMessage = "default";

    // getting the uid of the admin stored in shared preference
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mCtx);
    final String admin_uid = preferences.getString("uid","");

    DatabaseReference lastMsgRef = FirebaseDatabase.getInstance().getReference("Chats");
    lastMsgRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                Chats chats = snapshot.getValue(Chats.class);

                assert chats != null;

                // compares the uid of the admin and user and return the last message
                if(chats.getReceiver().equals(admin_uid) && chats.getSender().equals(user_id)
                        || chats.getReceiver().equals(user_id) && chats.getSender().equals(admin_uid)){
                    theLastMessage = chats.getMessage();
                }

            }

            // switch case for theLastMessage
            switch (theLastMessage){
                case "default":
                    last_msg.setText(R.string.no_message);
                    break;

                    default:
                        last_msg.setText(theLastMessage);
                        break;
            }

            theLastMessage = "default";
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            // display error message if one should occur
            Toast.makeText(mCtx, databaseError.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
    }
}

然后,在实例化适配器的类中,调用userIds列表的get方法,类似这样。

List<String> userIds = adapter.getUserIdsList();

通过这种方式,您可以对选定的用户ID列表进行任何操作