Reputation: 57
I am making a Group chat app in android, where the database is Firebase Realtime DB.
While registering users i successfully managed to save the user's "UserName" and "Email" inside "Users" node in Firebase.
The Question is how to get the Specific person name along with the chat when he/she posts a message ?
Here is my Registration Activity where i saved "Username" and "Email" in DB as a new user registers :
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
private void DOSignup() {
final String get_name = name.getText().toString().trim();
final String get_email = email.getText().toString().trim();
String get_password = password.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(get_email, get_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Log.e("Current User", firebaseUser.toString());
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
GetUserName getUserName = new GetUserName(get_name, get_email);
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(getUserName);
Toast.makeText(getApplicationContext(), "Registration successful!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Registration failed! Please try again later", Toast.LENGTH_LONG).show();
}
}
});
This is how the user posts message :
private void postMessages() {
databaseReference = FirebaseDatabase.getInstance().getReference("MessageTest");
Log.e("Reference is : ", String.valueOf(databaseReference));
String actual_msg = editText.getText().toString().trim();
ChatModel chatModel = new ChatModel(actual_msg);
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(chatModel).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChatActivity.this, "Message Sent Successfully", Toast.LENGTH_SHORT).show();
editText.setText("");
} else {
Toast.makeText(ChatActivity.this, "Message Sent Failed !", Toast.LENGTH_SHORT).show();
}
}
});
}
Here is my ChatModel Class :
public class ChatModel {
String messages;
public ChatModel() {
}
public ChatModel(String messages) {
this.messages = messages;
}
public String getMessages() {
return messages;
}
}
Here is my ChatAdapter class, where the Message are shown to users :
public class ChatAdapter extends FirebaseRecyclerAdapter<ChatModel, ChatAdapter.ViewHolder> {
Context context;
List<ChatModel> chatModelList;
public ChatAdapter(@NonNull FirebaseRecyclerOptions<ChatModel> options, Context context, List<ChatModel> chatModelList) {
super(options);
this.context = context;
this.chatModelList = chatModelList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_layout,
parent, false);
return new ViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull ChatModel model) {
ChatModel model1 = chatModelList.get(position);
GetUserName getUserName = new GetUserName();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
holder.messages.setText();
holder.userName.setText(databaseReference.getKey());
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView messages,userName;
public ViewHolder(@NonNull View itemView) {
super(itemView);
messages = itemView.findViewById(R.id.message_body);
userName = itemView.findViewById(R.id.userName); //This is a TextView where usernames need to be shown
}
}
Upvotes: 0
Views: 1371
Reputation: 598728
First of all, I'd highly recommend changing the structure of how you store the user data slightly. You're now using push()
to generate a unique key. But since each user already has a unique UID, you can store the users under that UID and make looking them up easier. To store it in this structure:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
GetUserName getUserName = new GetUserName(get_name, get_email);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference.child(uid).setValue(getUserName);
With that in place, let's get to using the user name when writing messages to the database.
You'll want to load the name of the current user when the app starts and they're signed in. The code for that would look something like this:
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference userReference = databaseReference.child(uid);
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("UserName").getValue(String.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
}
In the above snippet userName
is a member field on your activity class, so that you can access it other places too.
After this code runs, you can write the user name to the messages by:
ChatModel
classChatModel
instance.Upvotes: 2