我在我的Android应用上使用firebase。我创建了一个群聊应用程序。当用户创建组时,已将组名child添加到创建该组的用户的孩子中。群组所有者添加了一些朋友后,群组名称child已添加到朋友的孩子中。但是,当用户向组发送消息时,该消息将仅将发送方用户ID中的组子项推入。我希望当用户向组发送消息时,该消息将推送所有组成员子级。我该怎么办?
以下是我的代码:
GroupChatActivity.java:
package com.example.whatsapp2;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
public class GroupChatActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ImageButton SendMessageButton;
private EditText userMessageInput;
private ScrollView mScrollView;
private TextView displayTextMessages;
private String currentGroupName;
private FirebaseAuth mAuth;
private DatabaseReference UserRef, GroupNameRef, GroupMessageKeyRef;
private String currentUserID, currentUserName, currentDate, currentTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
//currentGroupName = getIntent().getExtras().getString("groupName");
currentGroupName = getIntent().getExtras().get("groupName").toString();
Toast.makeText(this,currentGroupName,Toast.LENGTH_SHORT).show();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
GroupNameRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(currentUserID).child(currentGroupName);
InitializeFields();
GetUserInfo();
SendMessageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SaveMessageInfoToDatabase();
userMessageInput.setText("");
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
@Override
protected void onStart() {
super.onStart();
GroupNameRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if(dataSnapshot.exists()){
DisplayMessages(dataSnapshot);
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if(dataSnapshot.exists()){
DisplayMessages(dataSnapshot);
}
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.group_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.group_add_friends_option){
SendUserToAddPeopleActivity();
}
return true;
}
private void SendUserToAddPeopleActivity() {
Intent addPeopleIntent = new Intent(this,AddPeopleActivity.class);
Bundle data1 = new Bundle();
data1.putString("groupName",currentGroupName);
addPeopleIntent.putExtras(data1);
startActivity(addPeopleIntent);
}
private void DisplayMessages(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()){
String chatDate = (String) ((DataSnapshot)iterator.next()).getValue();
String chatMessage = (String) ((DataSnapshot)iterator.next()).getValue();
String chatName = (String) ((DataSnapshot)iterator.next()).getValue();
String chatTime = (String) ((DataSnapshot)iterator.next()).getValue();
displayTextMessages.append(chatName+ " :\n"+chatMessage+"\n"+chatTime+" "+chatDate+"\n\n\n");
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}
private void SaveMessageInfoToDatabase() {
String message = userMessageInput.getText().toString();
String messageKey = GroupNameRef.push().getKey();
if(TextUtils.isEmpty(message)){
Toast.makeText(this,"Please write message first...",Toast.LENGTH_SHORT).show();
}
else {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDate = currentDateFormat.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTimeFormat = new SimpleDateFormat("hh:mm a");
currentTime = currentTimeFormat.format(calForTime.getTime());
HashMap<String,Object> groupMessageKey = new HashMap<>();
GroupNameRef.updateChildren(groupMessageKey);
GroupMessageKeyRef = GroupNameRef.child(messageKey);
HashMap<String,Object> messageInfoMap = new HashMap<>();
messageInfoMap.put("name",currentUserName);
messageInfoMap.put("message",message);
messageInfoMap.put("date",currentDate);
messageInfoMap.put("time",currentTime);
GroupMessageKeyRef.updateChildren(messageInfoMap);
}
}
private void GetUserInfo() {
UserRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
currentUserName = dataSnapshot.child("name").getValue().toString();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void InitializeFields() {
mToolbar = findViewById(R.id.group_chat_bar_layout);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(currentGroupName);
SendMessageButton =findViewById(R.id.send_message_button);
userMessageInput = findViewById(R.id.input_group_message);
mScrollView = findViewById(R.id.my_scroll_view);
displayTextMessages = findViewById(R.id.group_chat_text_display);
}
}
GroupsFragment.java:
package com.example.whatsapp2;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* A simple {@link Fragment} subclass.
*/
public class GroupsFragment extends Fragment {
private View groupFragmentView;
private ListView list_view;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_groups = new ArrayList<>();
private DatabaseReference GroupRef;
private FirebaseAuth mAuth;
private String currentUserId;
public GroupsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
groupFragmentView = inflater.inflate(R.layout.fragment_groups, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
GroupRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(currentUserId);
InitializeFields();
RetrieveAndDisplayGroups();
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String currentGroupName = parent.getItemAtPosition(position).toString();
Intent groupChatIntent = new Intent(getContext(),GroupChatActivity.class);
/*Bundle data1 = new Bundle();
/*if(groupChatIntent !=null){
data1.putString("groupName",currentGroupName);
groupChatIntent.putExtras(data1);
}*/
/*data1.putString("groupName",currentGroupName);
groupChatIntent.putExtras(data1);*/
groupChatIntent.putExtra("groupName",currentGroupName);
startActivity(groupChatIntent);
}
});
return groupFragmentView;
}
private void RetrieveAndDisplayGroups() {
GroupRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<>();
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()){
set.add(((DataSnapshot)iterator.next()).getKey());
}
list_of_groups.clear();
list_of_groups.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void InitializeFields() {
list_view = groupFragmentView.findViewById(R.id.list_view);
arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1,list_of_groups);
list_view.setAdapter(arrayAdapter);
}
}