Android - Firebase - Send Users to Chat Room
Asked Answered
D

3

0

Aim

Allowing the Users to access their selected Group Chat. Once the user clicks on the Group Chat name, they will be entered into that Group Chat.

Database Tree

enter image description here

As shown in the Database Tree, the Currently Signed In user will be shown a list of Group Chat names that have been created.

I have an Admin Account to create these Group Chats for the users.

The Android, Asia, and Europe group chats that are seen within the Database ARE NOT fixed variables. They are names. A newly Group Chat name could be "Earth".

Therefore there is no way of calling it by a variable other than calling it by the Node itself.

Screenshot of Application

  1. List of Group Chats 2. Entering a Group Chat

image2 image3

Flow of Activities

  1. GroupFragment ---> Chat Activity

  2. GroupFragment <--- Chat Activity

Flow of Application

User--->LoginActivity--->UserActivity--->GroupFrag--->GroupChatActivity

At the (GroupFrag--->GroupChatActivity) The user must select a Group Chat name within the GroupFrag to enter the GroupChatActivity

The user must select a Group Chat name within the GroupFrag to enter the GroupChatActivity

Description

  1. The users will be able to select a Group Chat name (from GroupFragment) and the app will bring the user into the Group Chat itself (into Chat Activity). The User will be able to go back to the GroupFragment and select another desired Group.

(Group Chat names are NOT FIXED -- They're not a node that can be called from)

Problem

  1. I am unable to select the Group Chat names after it was prompt within the Fragment, which will then bring me to the Group Chat.

Group Fragment

 @Override
    public void onStart() {
        super.onStart();


        class GroupAdapter extends RecyclerView.Adapter<GroupAdapter.MyHolder> {

            ArrayList<String> list;

            public GroupAdapter(ArrayList<String> list) {
                this.list = list;
            }


            @Override
            public GroupAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_groups, parent, false);

                return new MyHolder(view);
            }

            @Override
            public void onBindViewHolder(MyHolder holder, int position) {
                holder.setText(list.get(position));
            }

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

            class MyHolder extends RecyclerView.ViewHolder {
                TextView nameTextView;

                public MyHolder(View itemView) {
                    super(itemView);
                    nameTextView = itemView.findViewById(R.id.groupChatNameTxt);
                }

                public void setText(String groupName) {
                    nameTextView.setText(groupName);
                }
            }
        }

        jGroupsDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                ArrayList<String> groupChatNames = new ArrayList<>();
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    groupChatNames.add(child.getKey());
                }
                GroupAdapter adapter = new GroupAdapter(groupChatNames);
                jGroupChatList.setAdapter(adapter);

                //I'm not sure where to write a code for userID
                //final String usersID = getRef(position).getKey();
// When the user clicks on one of the group chat names, he/she will be sent to the Chat Activity

                jGroupChatList.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intentUserProfile = new Intent(getActivity(), ChatActivity.class);
                        intentUserProfile.putExtra("groupChatName",groupName);
                        intentUserProfile.putExtra("neighbourhood", neighbourhood);
                        intentUserProfile.putExtra("usersName", usersName);
                        intentUserProfile.putExtra("usersID", usersID);
                        startActivity(intentUserProfile);
                    }
                });
            }

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

Chat Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        jGroupChatName = getIntent().getExtras().get("groupChatName").toString();
        jUserID = getIntent().getExtras().get("usersID").toString();
        jUserName = getIntent().getExtras().get("usersName").toString();
        jUserNeighbourhood = getIntent().getExtras().get("neighbourhood").toString();

        jChatRoot = FirebaseDatabase.getInstance().getReference().child(jGroupChatName);

        jChatToolbar = (Toolbar) findViewById(R.id.allUSersToolBar);
        setSupportActionBar(jChatToolbar);
        getSupportActionBar().setTitle(jGroupChatName); // Show the name of the selected group name
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        }

Additional Comments

  • Online Tutorial

I have watched an Android Firebase Group Chat tutorial on youtube. The link is https://www.youtube.com/watch?v=wVCz1a3ogqk. But it does not provide some the features/ functions whic I am trying to implement.

  • Linked Question

Android - Firebase - Prompting Group Chat Names

Future Implementations

For future implementations, I would like to send and retrieve the messages and prompt it into the group chat for the users to view like a real group chat. But of course, I will leave that for another Question.

Damalis answered 26/9, 2017 at 20:25 Comment(8)
Your groups are static or dynamicBeckibeckie
My group names are dynamic. If I were to add in a group chat called "Earth", there will then be a group chat called "Earth". The names are not Fixed. Should I add in the whole code for the class? Right now I've only added in the important ones. Meaning that I've excluded the imports, privates, and etc. The codes that I've posted are just the functions. And Thank you for replying to this question =DDamalis
Just to clarify - you have a listView that corresponds to the Group Chat node? In the example the listView has 3 values? And you want to say when a user clicks on the listView then their Username (a variable) is appended to the Group Chat node?Forsook
@Forsook yes that's what I intend to do. Its like Group Chat. If I were to enter a group chat, my "name" from the users node will be retrieved and brought into the "Group Chat Name" within the "Group Chat" nodeDamalis
@TheStudent123 so you have access to your listView so you can get the title of the item clicked and pass it to the chatview activity. That means when users enter the chat room they will be in the correct room based on their selection. When you do this just add the uuid of the user to the selected item using updateValues?Forsook
@Forsook Yes!!! That's exactly what I mean. But I do not know how to write the code for that or what algorithm is required. Right now I have my listView, but the user isn't able to click on the Group Chat name to enter into that group chat.Damalis
1: Where do you keep which users belong to which chat? 2: Where and how do you get neighbourhood, usersName and usersID?Tabloid
@Tabloid 1: I keep that information inside the Group Chat node, under the group in which the user selected to join 2: I get the neighbourhood and UserName from the Users node. I don't know how to to do it but Thank you for your answer =DDamalis
T
1

You can update your adapter and viewholder implementation as follows:

public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {

    Context context;
    ArrayList<String> list;

    public Adapter(Context context, ArrayList<String> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public Adapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_groups, parent, false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.setText(list.get(position));
    }

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

    class MyHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String groupName = list.get(getAdapterPosition());
                Intent intentUserProfile = new Intent(context, MainActivity.class);
                intentUserProfile.putExtra("groupChatName", groupName);
                // If fixed, you should pass these values to adapter's constructor
                // intentUserProfile.putExtra("neighbourhood", neighbourhood);
                // intentUserProfile.putExtra("usersName", usersName);
                // intentUserProfile.putExtra("usersID", usersID);
                context.startActivity(intentUserProfile);
            }
        };

        public MyHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(onClickListener);
            nameTextView = (TextView) itemView.findViewById(R.id.groupChatNameTxt);
        }

        public void setText(String groupName) {
            nameTextView.setText(groupName);
        }
    }
}

You also have to update this line in your GroupFragment:

GroupAdapter adapter = new GroupAdapter(getActivity(), groupChatNames);

This is another solution that you can implement inside your fragment so that you can put extras in intent (actually modified from your former question):

@Override
public void onStart() {
    super.onStart();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference groupChatsRef = rootRef.child("Group Chats");
    FirebaseRecyclerAdapter<String, GroupChatViewHolder> chatAdapter = new FirebaseRecyclerAdapter<String, GroupChatViewHolder>(
            String.class,
            R.layout.layout_groups,
            GroupChatViewHolder.class,
            groupChatsRef) {
        protected void populateViewHolder(GroupChatViewHolder viewHolder, String model, int position) {
            final String groupChatName = this.getRef(position).getKey();
            viewHolder.setName(groupChatName);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intentUserProfile = new Intent(getActivity(), ChatActivity.class);
                    intentUserProfile.putExtra("groupChatName", groupChatName);
                    intentUserProfile.putExtra("neighbourhood", neighbourhood);
                    intentUserProfile.putExtra("usersName", usersName);
                    intentUserProfile.putExtra("usersID", usersID);
                    startActivity(intentUserProfile);
                }
            });
        }
    };
    jGroupChatList.setAdapter(chatAdapter);
}

Note that it handles your string-string group chat entries in your DB as key-value pairs.

Tabloid answered 27/9, 2017 at 22:20 Comment(1)
Hello again @Mehmed, I must trouble you again for another question as I'm not receiving any answers. The link is: stackoverflow.com/questions/46471541/… I hope you can find the time to help me out. Thank youDamalis
F
1
    public class group_name_list_adapter extends RecyclerView.Adapter<group_name_list_adapter.ViewHolder> {

        private List< group_name_list> listItems;
        private Context context;
        OnItemClickListener onItemClickListener;

        public group_name_list_adapter(List<group_name_list> listItems, Context context) {
            this.listItems = listItems;
            this.context = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.group_name_list, parent, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            group_name_list listItem = listItems.get(position);

            holder.txtTitle.setText(listItem.getTxtTitle());
            holder.txtTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onGroupNameClick(position);
                }
            });
        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {

            public TextView txtTitle;

            public ViewHolder(View itemView) {
                super(itemView);
                txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            }
        }
        public void setOnItemClickListener(OnItemClickListener onItemClickListener){
            this.onItemClickListener = onItemClickListener;
        }

        public interface OnItemClickListener{
            void onGroupNameClick(int position); 
        }
    }



    public class group_name_list {

        private String txtTitle;

        public group_name_list(String txtTitle) {
            this.txtTitle = txtTitle;
        }

        public String getTxtTitle() {
            return txtTitle;
        }
    }



    public class ChatActivity implements group_name_list_adapter.OnItemClickListener

    private RecyclerView recyclerGroupName;
    private group_name_list_adapter groupNameAdapter;
    private List<group_name_list> group_name_List;
    private List<String> groupNameKeyList; //This is optional – this is used if you wanted the group chats to have the same name instead of overwriting the groupchat when creating.

    Inside your Firebase call:

    group_name_List.removeAll(group_name_List t);
    groupNameKeyList.removeAll(groupNameKeyList);
    //Depending on your firebase reference. This could just be dataSnapshot.getChildren()
    for (DataSnapshot child : dataSnapshot.child("Group Chats").getChildren()){


        if (!child.getKey().equals(null)){
            groupNameKeyList.add(child.getKey().toString()); //Again this is optional
        }

        group_name_list newGroupList = child.getValue();
        );
        groupNameList.add(newGroupList);
    }
    recyclerGroupName.setAdapter(groupNameAdapter);

    gLayoutAttribute = new GridLayoutManager(getActivity(), 1);
    recyclerGroupName = (RecyclerView) rootView.findViewById(R.id.recyclerGroupName);
    recyclerGroupName.setHasFixedSize(true);
    recyclerGroupName.setLayoutManager(new LinearLayoutManager(this.getContext()));
    recyclerGroupName.setLayoutManager(gLayoutAttribute);


@Override
    public void onAttributeClick(int position) {
        Intent intentUserProfile = new Intent(getActivity(), ChatActivity.class);
        intentUserProfile.putExtra("groupChatName",groupName);
        intentUserProfile.putExtra("neighbourhood", neighbourhood);
        intentUserProfile.putExtra("usersName", usersName);
        intentUserProfile.putExtra("usersID", usersID);
        intent.putExtra("name", groupList.get(position).toString());
        //intent.putExtra("name", groupListKeyList.get(position).toString()); this is your optional key
        startActivity(intentUserProfile);
    }
Forsook answered 27/9, 2017 at 19:1 Comment(7)
I got this error, Cannot resolve method 'setOnItemClickListener(anonymous android.widget.AdapterView.OnItemClickListener)' and also I could not resolve the get(position) Please help with thisDamalis
Okay thank you. Oh a Firebase Listener? Alright I'll try that =DDamalis
Tell me if that works for you - at the top of your GroupChat add implements GroupAdapter.OnItemClickListener. You may need to move somethings around. I can help you better in a chat room.Forsook
I have tried implementing implements GroupAdapter.OnItemClickListener but it says "Cannot resolve symbol 'OnItemClickListener". Yeah!! I would like to discuss this in a chat room with you too but I can't find that chat option :( Should I post the whole code? That way you will be able to have exactly the same file as me. This question is also linked to #46413382Damalis
Let me know if that helps you or not.Forsook
Let us continue this discussion in chat.Forsook
Thank you for your answer and patience in explaining your codes to me Torewin!! =DDamalis
T
1

You can update your adapter and viewholder implementation as follows:

public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {

    Context context;
    ArrayList<String> list;

    public Adapter(Context context, ArrayList<String> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public Adapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_groups, parent, false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.setText(list.get(position));
    }

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

    class MyHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String groupName = list.get(getAdapterPosition());
                Intent intentUserProfile = new Intent(context, MainActivity.class);
                intentUserProfile.putExtra("groupChatName", groupName);
                // If fixed, you should pass these values to adapter's constructor
                // intentUserProfile.putExtra("neighbourhood", neighbourhood);
                // intentUserProfile.putExtra("usersName", usersName);
                // intentUserProfile.putExtra("usersID", usersID);
                context.startActivity(intentUserProfile);
            }
        };

        public MyHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(onClickListener);
            nameTextView = (TextView) itemView.findViewById(R.id.groupChatNameTxt);
        }

        public void setText(String groupName) {
            nameTextView.setText(groupName);
        }
    }
}

You also have to update this line in your GroupFragment:

GroupAdapter adapter = new GroupAdapter(getActivity(), groupChatNames);

This is another solution that you can implement inside your fragment so that you can put extras in intent (actually modified from your former question):

@Override
public void onStart() {
    super.onStart();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference groupChatsRef = rootRef.child("Group Chats");
    FirebaseRecyclerAdapter<String, GroupChatViewHolder> chatAdapter = new FirebaseRecyclerAdapter<String, GroupChatViewHolder>(
            String.class,
            R.layout.layout_groups,
            GroupChatViewHolder.class,
            groupChatsRef) {
        protected void populateViewHolder(GroupChatViewHolder viewHolder, String model, int position) {
            final String groupChatName = this.getRef(position).getKey();
            viewHolder.setName(groupChatName);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intentUserProfile = new Intent(getActivity(), ChatActivity.class);
                    intentUserProfile.putExtra("groupChatName", groupChatName);
                    intentUserProfile.putExtra("neighbourhood", neighbourhood);
                    intentUserProfile.putExtra("usersName", usersName);
                    intentUserProfile.putExtra("usersID", usersID);
                    startActivity(intentUserProfile);
                }
            });
        }
    };
    jGroupChatList.setAdapter(chatAdapter);
}

Note that it handles your string-string group chat entries in your DB as key-value pairs.

Tabloid answered 27/9, 2017 at 22:20 Comment(1)
Hello again @Mehmed, I must trouble you again for another question as I'm not receiving any answers. The link is: stackoverflow.com/questions/46471541/… I hope you can find the time to help me out. Thank youDamalis
B
0

Try according to this

  1. Suppose you've created 5 user's in FirebaseDatabasewith different UID's
  2. In this step you have to get all user's from Firebase and display it in RecyclerView
  3. In Recyclerview's adapter class in onBindViewHolder' you have to do like add and remove` users from list which you generated at the time creating group.
  4. In this step you've to search firebaseDatabase user's Uid which is currently logged in and if your UID is matched found in any Group then you need to get the Group-name .

Happy to help you

Beckibeckie answered 27/9, 2017 at 18:30 Comment(10)
But I do not intend to prompt the users into a list view to view them. What I intend is this: FlowDamalis
Flow User--->LoginActivity--->UserActivity--->GroupFrag--->GroupChatActivity At the (GroupFrag--->GroupChatActivity) The user must select a Group Chat name within the GroupFrag to enter the GroupChatActivityDamalis
User can'nt able to create our own group if not then who create groupBeckibeckie
Only the Admin can create the group. This part of the code is the "Linked Question" that I added to my question.Damalis
Each of the user can create own group or notBeckibeckie
The User can't create their own groupDamalis
Then who can create the groupBeckibeckie
Only the Admin can create the group. The Admin is not included within the Users database as the Admin is hardcodedDamalis
Ok now fine,can you get list of users from the admin account ?Beckibeckie
Let us continue this discussion in chat.Beckibeckie

© 2022 - 2024 — McMap. All rights reserved.