1

enter image description here

I am developing chat app and need help regarding its group structure.

I already manage structure till groupIcon but now how to create members structure with 0 ... 1... 2... etc...?

Here is my code :

private void createGroup(String strGroupName) {

        RootRef = FirebaseDatabase.getInstance().getReference("GroupDetail");

        String strGroupID = RootRef.push().getKey();

        HashMap<String, String> groupMap = new HashMap<>();
        groupMap.put("_id", group_id);
        groupMap.put("adminId", admin_id);
        groupMap.put("adminName", admin_name);
        groupMap.put("createdAt", created_at);
        groupMap.put("groupIcon", group_icon);

        RootRef.child(strGroupID).setValue(groupMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        Toast.makeText(activity, "Group created 
successfully",Toast.LENGTH_SHORT).show();
                    }
                });
    }

1 Answers1

0

In the members property you have an array. I'd actually suggest first changing that model to a map like this:

members: {
  "5c6260...63d00": true,
  "5c6262...63d02": true
}

Reason for that are that you'll typically want each user to be a member of the chat room at most once, while an array can have the same value multiple times. Using a map automatically prevents this problem, since keys are guaranteed to be unique in a map (and in Firebase's JSON). For more on this, also see my answer here: Firebase query if child of child contains a value

The above structure you can write with a Map<String, boolean> in Java:

Map<String, boolean> members = new Map<>();
members.put("5c6260...63d00", true);
members.put("5c6262...63d02", true);
groupMap.put("members", members);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807