Output:
1/ Create an empty project
2/ Connect your app with Firebase
2.1/ Connect Firebase: You can connect Firebase via Android Studio Firebase Tool Assistance or Manually. For this project, I create and connect the project manually.
2.1/ After creating the project in Firebase first click on the Android icon to connect the app with your project. Here, provide your app package name and click next, next, and lastly, go to the console.
3/ Add Firebase authentication and real-time database SDK to your app ( you can use the Firebase assistance tool )
4/Open your Firebase project which you already connect for this project
5/ Add an authentication provider: Email/Password
6/ Create real-time database and set rules for read and write true
Now let's start our code for the project
7/ Create an activity SplashActivity:
7.1/ Modify activity_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SplashActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat App"
android:layout_gravity="center"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat with others"
android:layout_gravity="center"
android:textSize="16sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
7.2/ Modify SplashActivity.java
package com.example.chatapp;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(() -> {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
finish();
}, 3000);
}
}
8/ Create an activity LoginActivity:
8.1/ Modify activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".LoginActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
>
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Email here" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter Your password here" />
</LinearLayout>
<Button
app:layout_constraintTop_toBottomOf="@+id/linearlayout"
android:layout_marginTop="16dp"
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
/>
<TextView
android:id="@+id/or"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/loginButton"
app:layout_constraintStart_toStartOf="@id/loginButton"
app:layout_constraintEnd_toEndOf="@id/loginButton"
android:layout_marginTop="16dp"
android:text="OR"
android:textSize="22sp"
/>
<TextView
android:id="@+id/registerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/or"
app:layout_constraintStart_toStartOf="@id/or"
app:layout_constraintEnd_toEndOf="@id/or"
android:layout_marginTop="16dp"
android:text="Create an account"
android:textSize="22sp"
android:textColor="#21608B"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
8.2/ Modify LoginActivity.xml
package com.example.chatapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView registerButton;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.loginButton);
registerButton = findViewById(R.id.registerButton);
auth = FirebaseAuth.getInstance();
loginButton.setOnClickListener(v -> {
String emailTxt = email.getText().toString();
String passwordTxt = password.getText().toString();
loginUser(emailTxt, passwordTxt);
});
registerButton.setOnClickListener(v -> {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
});
}
private void loginUser(String email, String password) {
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = auth.getCurrentUser();
if(currentUser != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
9/ Create an activity RegistrationActivity:
9.1/ Modify activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".LoginActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
>
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Name here" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Email here" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter Your password here" />
</LinearLayout>
<Button
app:layout_constraintTop_toBottomOf="@+id/linearlayout"
android:layout_marginTop="16dp"
android:id="@+id/registerButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
/>
<TextView
android:id="@+id/or"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/registerButton"
app:layout_constraintStart_toStartOf="@id/registerButton"
app:layout_constraintEnd_toEndOf="@id/registerButton"
android:layout_marginTop="16dp"
android:text="OR"
android:textSize="22sp"
/>
<TextView
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/or"
app:layout_constraintStart_toStartOf="@id/or"
app:layout_constraintEnd_toEndOf="@id/or"
android:layout_marginTop="16dp"
android:text="Login existing account"
android:textSize="22sp"
android:textColor="#21608B"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
9.2/ Modify RegistrationActivity.xml
package com.example.chatapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class RegistrationActivity extends AppCompatActivity {
private EditText email, password, name;
private Button registerButton;
private TextView loginButton;
private FirebaseAuth mAuth;
private DatabaseReference userRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
name = findViewById(R.id.name);
registerButton = findViewById(R.id.registerButton);
loginButton = findViewById(R.id.loginButton);
mAuth = FirebaseAuth.getInstance();
userRef = FirebaseDatabase.getInstance().getReference("Users");
registerButton.setOnClickListener(v -> {
String emailTxt = email.getText().toString();
String passwordTxt = password.getText().toString();
String nameTxt = name.getText().toString();
registerUser(emailTxt, passwordTxt, nameTxt);
});
loginButton.setOnClickListener(v -> {
startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
});
}
private void registerUser(String email, String password, String name) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
String uid = FirebaseAuth.getInstance().getUid();
userRef.child(uid).setValue(new User(uid, email, name));
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(RegistrationActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
}
});
}
}
10/ MainActivity:
10.1/ Modify activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User List"
android:layout_gravity="center"
android:textColor="@color/white"
android:layout_weight="1"
/>
<Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:layout_gravity="center"
android:textColor="@color/white"
/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewUsers"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:listitem="@layout/item_user" />
</androidx.constraintlayout.widget.ConstraintLayout>
10.2/ Modify MainActivity.xml
package com.example.chatapp;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.List;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference userRef;
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> userList;
private Button logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
userRef = FirebaseDatabase.getInstance().getReference("Users");
recyclerView = findViewById(R.id.recyclerViewUsers);
logout = findViewById(R.id.logout);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userList = new ArrayList<>();
userAdapter = new UserAdapter(userList, MainActivity.this);
recyclerView.setAdapter(userAdapter);
loadUsers();
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logOut();
}
});
}
private void loadUsers() {
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
userList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
User user = dataSnapshot.getValue(User.class);
if(!user.getUserId().equals(mAuth.getCurrentUser().getUid()))
{
userList.add(user);
}
}
userAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to load users.", Toast.LENGTH_SHORT).show();
}
});
}
public void logOut() {
mAuth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
11/ Create item layout item_user.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
>
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unknown"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Email"
android:textSize="16sp"
android:textColor="@android:color/black"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</LinearLayout>
<Button
android:id="@+id/btnChat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
12/ Create Model Class User:
package com.example.chatapp;
public class User {
private String userId;
private String email;
private String name;
public User() {
}
public User(String userId, String email , String name) {
this.userId = userId;
this.email = email;
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
13/ Create Adapter Class UserAdapter:
package com.example.chatapp;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
private List<User> userList;
private Context context;
public UserAdapter(List<User> userList, Context context) {
this.userList = userList;
this.context = context;
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_user, parent, false);
return new UserViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
User user = userList.get(position);
holder.username.setText(user.getName());
holder.useremail.setText(user.getEmail());
holder.btnChat.setOnClickListener(v -> {
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra("receiverId", user.getUserId());
context.startActivity(intent);
});
}
@Override
public int getItemCount() {
return userList.size();
}
public static class UserViewHolder extends RecyclerView.ViewHolder {
TextView username, useremail;
Button btnChat;
public UserViewHolder(@NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
useremail = itemView.findViewById(R.id.useremail);
btnChat = itemView.findViewById(R.id.btnChat);
}
}
}
14/ Create an activity ChatActivity:
14.1/ Modify activity_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbarChat"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:title="Chat"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewMessages"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toBottomOf="@id/toolbarChat"
app:layout_constraintBottom_toTopOf="@id/messageInputContainer"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:listitem="@layout/chat_item" />
<LinearLayout
android:id="@+id/messageInputContainer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<EditText
android:id="@+id/editTextMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type your message"
android:padding="10dp"
android:textSize="16sp" />
<Button
android:id="@+id/buttonSendMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Message"
android:layout_marginStart="8dp"
android:padding="8dp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
14.2/ Modify ChatActivity.xml
package com.example.chatapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.List;
public class ChatActivity extends AppCompatActivity {
private EditText editTextMessage;
private Button buttonSendMessage;
private RecyclerView recyclerViewMessages;
private MessageAdapter messageAdapter;
private List<Message> messageList;
private DatabaseReference chatDatabaseReference;
private FirebaseAuth firebaseAuth;
private FirebaseUser currentUser;
private String receiverId;
private String currentUserId;
private String chatId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSendMessage = findViewById(R.id.buttonSendMessage);
recyclerViewMessages = findViewById(R.id.recyclerViewMessages);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
currentUserId = currentUser.getUid();
receiverId = getIntent().getStringExtra("receiverId");
chatId = generateChatId(currentUserId, receiverId);
chatDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats").child(chatId);
messageList = new ArrayList<>();
messageAdapter = new MessageAdapter(messageList, currentUserId);
recyclerViewMessages.setLayoutManager(new LinearLayoutManager(this));
recyclerViewMessages.setAdapter(messageAdapter);
loadMessages();
buttonSendMessage.setOnClickListener(view -> {
String messageText = editTextMessage.getText().toString().trim();
if (!messageText.isEmpty()) {
sendMessage(messageText);
editTextMessage.setText("");
}
});
}
private void loadMessages() {
chatDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
messageList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Message chatMessage = dataSnapshot.getValue(Message.class);
if (chatMessage != null) {
messageList.add(chatMessage);
}
}
messageAdapter.notifyDataSetChanged();
recyclerViewMessages.scrollToPosition(messageList.size() - 1);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void sendMessage(String messageText) {
Message chatMessage = new Message(currentUserId, receiverId, messageText);
chatDatabaseReference.push().setValue(chatMessage);
}
private String generateChatId(String senderId, String receiverId) {
if (senderId.compareTo(receiverId) > 0) {
return senderId + "_" + receiverId;
} else {
return receiverId + "_" + senderId;
}
}
}
15/ Create item layout chat_tem.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<LinearLayout
android:id="@+id/messageSentContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"android:layout_gravity="end"android:background="@drawable/sent_message_bg"
android:padding="10dp"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="@+id/textViewSentMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message sent"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/messageReceivedContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="@drawable/received_message_bg"
android:padding="10dp"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="@+id/textViewReceivedMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message received"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
15/ Create drawable layout received_message_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#E0E0E0" />
<corners android:radius="12dp" />
</shape>
16/ Create drawable layout sent_message_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#4CAF50" />
<corners android:radius="12dp" />
</shape>
17/ Create Model Class Message:
package com.example.chatapp;
public class Message {
private String senderId;
private String receiverId;
private String message;
public Message() {}
public Message(String senderId, String receiverId, String message) {
this.senderId = senderId;
this.receiverId = receiverId;
this.message = message;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
18/ Create Adapter Class MessageAdapter:
package com.example.chatapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {
private List<Message> messageList;
private String currentUserId;
public MessageAdapter(List<Message> messageList, String currentUserId) {
this.messageList = messageList;
this.currentUserId = currentUserId;
}
@NonNull
@Override
public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item, parent, false);
return new MessageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
Message message = messageList.get(position);
if (message.getSenderId().equals(currentUserId)) {
holder.messageSentContainer.setVisibility(View.VISIBLE);
holder.messageReceivedContainer.setVisibility(View.GONE);
holder.textViewSentMessage.setText(message.getMessage());
} else {
holder.messageReceivedContainer.setVisibility(View.VISIBLE);
holder.messageSentContainer.setVisibility(View.GONE);
holder.textViewReceivedMessage.setText(message.getMessage());
}
}
@Override
public int getItemCount() {
return messageList.size();
}
public static class MessageViewHolder extends RecyclerView.ViewHolder {
LinearLayout messageSentContainer, messageReceivedContainer;
TextView textViewSentMessage;
TextView textViewReceivedMessage;
public MessageViewHolder(@NonNull View itemView) {
super(itemView);
messageSentContainer = itemView.findViewById(R.id.messageSentContainer);
textViewSentMessage = itemView.findViewById(R.id.textViewSentMessage);
messageReceivedContainer = itemView.findViewById(R.id.messageReceivedContainer);
textViewReceivedMessage = itemView.findViewById(R.id.textViewReceivedMessage);
}
}
}