Skip to content
Pull requests
Issues
Marketplace
Explore
@AdityaV025
AdityaV025 /
Mentzy
Private
1
0
0
Code
Issues
Pull requests
Actions
Projects
Security
Insights
Settings
Mentzy/app/src/main/java/com/mentzy/android/ui/ChatActivity.java /
@AdityaV025
AdityaV025 refactor the structure, add the proguard to both the debug and releas…
Latest commit 88a981f on 18 Feb
History
1 contributor
651 lines (611 sloc) 31.8 KB
package com.mentzy.android.ui;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mentzy.android.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.mentzy.android.enums.FireStoreCollections;
import com.mentzy.android.models.ChatModel;
import com.mentzy.android.utils.TimeStampHandler;
import com.mentzy.android.utils.UserEmailProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mSendMessageEditText;
private ImageView mSendBtn,mImageAttachmentBtn,mFileAttachmentBtn;
private String emailId,chat_channel_id,name,title,profile_image, chatting_with_uid,msgTime,msgDate;
private FirebaseFirestore db;
private FirestoreRecyclerAdapter<ChatModel, ChatHolder> adapter;
LinearLayoutManager linearLayoutManager;
private RecyclerView mChatsRecyclerView;
private TextView mChatUserName,mChatUserTitle;
private CircleImageView mChatUserProfileImage;
private Uri mImageUri;
private StorageReference mAttachImageRef,mAttachFileRef, filePath;
private ProgressDialog mProgressDialog;
private ProgressDialog mChatProgressDialog;
private TimeStampHandler timeStampHandler;
private static final int IMAGE_PICK_REQUEST_CODE = 123;
private static final int FILE_PICK_REQUEST_CODE = 456;
ListenerRegistration listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
init();
fetchChatMessages();
}
private void init() {
mChatProgressDialog = new ProgressDialog(this);
mChatProgressDialog.setMessage("Fetching Messages...");
mChatProgressDialog.show();
timeStampHandler = new TimeStampHandler();
chat_channel_id = getIntent().getStringExtra("chat_channel_id");
name = getIntent().getStringExtra("name");
title = getIntent().getStringExtra("title");
chatting_with_uid = getIntent().getStringExtra("chatting_with_uid");
profile_image = getIntent().getStringExtra("profile_image");
mChatUserName = findViewById(R.id.chatUserTitle);
mChatUserName.setText(name);
mChatUserTitle = findViewById(R.id.chatUserBottom);
mChatUserTitle.setText(title);
mChatUserProfileImage = findViewById(R.id.chatUserProfileImage);
Glide.with(this)
.load(profile_image)
.placeholder(R.drawable.placeholder_image)
.into(mChatUserProfileImage);
emailId = UserEmailProvider.getUserEmail(this);
db = FirebaseFirestore.getInstance();
mProgressDialog = new ProgressDialog(this);
mAttachImageRef = FirebaseStorage.getInstance().getReference();
mAttachFileRef = FirebaseStorage.getInstance().getReference();
mChatsRecyclerView = findViewById(R.id.chatsRecyclerView);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
linearLayoutManager.setSmoothScrollbarEnabled(true);
mChatsRecyclerView.setLayoutManager(linearLayoutManager);
mChatsRecyclerView.getRecycledViewPool().setMaxRecycledViews(0,0);
mSendMessageEditText = findViewById(R.id.sendMessageEditText);
mSendBtn = findViewById(R.id.sendIcon);
RelativeLayout mChatPersonInfoContainer = findViewById(R.id.chatPersonInfoContainer);
mChatPersonInfoContainer.setOnClickListener(v -> {
// 2Do Implement ChatPerson Code...
});
mImageAttachmentBtn = findViewById(R.id.imageAttachmentIcon);
mFileAttachmentBtn = findViewById(R.id.attachmentIcon);
mSendBtn.setOnClickListener(this);
mImageAttachmentBtn.setOnClickListener(this);
mFileAttachmentBtn.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.sendIcon:
sendMessage();
break;
case R.id.imageAttachmentIcon:
sendImageAttachment();
break;
case R.id.attachmentIcon:
sendFileAttachment();
break;
}
}
private void fetchChatMessages() {
Query query = db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).collection(String.valueOf(FireStoreCollections.Messages)).orderBy("timestamp",Query.Direction.ASCENDING);
listener = query.addSnapshotListener((value, error) -> {
if (Objects.requireNonNull(value).isEmpty()){
mChatProgressDialog.dismiss();
}
});
FirestoreRecyclerOptions<ChatModel> chatModel = new FirestoreRecyclerOptions.Builder<ChatModel>()
.setQuery(query, ChatModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<ChatModel, ChatHolder>(chatModel) {
@SuppressLint("SetTextI18n")
@Override
protected void onBindViewHolder(@NonNull ChatHolder holder, int i, @NonNull ChatModel model) {
if (adapter != null){
showDateOrNot(holder,model);
setSeenStatus(adapter);
}
if (model.getFrom_uid().equals(emailId)){
holder.receiverMessageContainer.setVisibility(View.GONE);
holder.senderMessage.setText(model.getMessage());
holder.timeStampReceiver.setVisibility(View.GONE);
holder.timeStampSenderText.setText(model.getChat_time());
String ImageUrl = model.getImage_message();
String fileUrl = model.getFile_message();
if (!ImageUrl.equals("none")){
holder.senderMessageImageContainer.setVisibility(View.VISIBLE);
Glide.with(getApplicationContext())
.load(ImageUrl)
.apply(new RequestOptions().override(250,200))
.into(holder.senderImageAttach);
holder.senderMessageImageContainer.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), ChatImageView.class);
intent.putExtra("image_src",ImageUrl);
startActivity(intent);
});
}else if(!fileUrl.equals("none")){
long fileSizeInBytes = model.getFile_size_in_bytes();
String fileType = model.getFile_type();
String fileName = model.getFile_name();
holder.fileIconSender.setImageDrawable(showFileIcon(fileName,"sender"));
holder.senderFileContainer.setVisibility(View.VISIBLE);
holder.senderFileContainer.setOnClickListener(v -> {
openFile(fileUrl,fileType,fileName);
});
holder.senderFileName.setText(fileName);
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
holder.senderFileExtension.setText(fileExtension);
holder.senderFileSize.setText(calculateFileSize(fileSizeInBytes));
}
}else if(!model.getFrom_uid().equals(emailId) && model.getImage_message() != null && model.getFile_message() != null){
holder.senderMessageContainer.setVisibility(View.GONE);
holder.receiverMessage.setText(model.getMessage());
holder.timeStampSenderText.setVisibility(View.GONE);
holder.timeStampReceiver.setText(model.getChat_time());
String ImageUrl = model.getImage_message();
String fileUrl = model.getFile_message();
if (!ImageUrl.equals("none")){
holder.receiverMessageImageContainer.setVisibility(View.VISIBLE);
Glide.with(getApplicationContext())
.load(model.getImage_message())
.apply(new RequestOptions().override(250,200))
.into(holder.receiverImageAttach);
holder.receiverMessageImageContainer.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), ChatImageView.class);
intent.putExtra("image_src",ImageUrl);
startActivity(intent);
});
}else if(!fileUrl.equals("none")){
long fileSizeInBytes = model.getFile_size_in_bytes();
String fileType = model.getFile_type();
String fileName = model.getFile_name();
holder.fileIconReceiver.setImageDrawable(showFileIcon(fileName,"receiver"));
holder.receiverFileContainer.setVisibility(View.VISIBLE);
holder.receiverFileContainer.setOnClickListener(v -> {
openFile(fileUrl,fileType,fileName);
});
holder.receiverFileName.setText(fileName);
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
holder.receiverFileExtension.setText(fileExtension);
holder.receiverFileSize.setText(calculateFileSize(fileSizeInBytes));
}
}
}
@NonNull
@Override
public ChatHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_chat_bubble, parent, false);
return new ChatHolder(view);
}
};
scrollToBottom(adapter);
adapter.startListening();
mChatsRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private Drawable showFileIcon(String fileName,String userType) {
Drawable fileIcon = null;
if (fileName.endsWith(".docx") || fileName.endsWith(".doc")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.word_icon);
}else if(fileName.endsWith(".ppt") || fileName.endsWith(".pptx")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.ppt_icon);
}else if(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.excel_icon);
}else if(fileName.endsWith(".pdf")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.pdf_icon);
}else if(fileName.endsWith(".zip")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.zip_icon);
}else if(fileName.endsWith(".rar")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.rar_icon);
}else {
if (userType.equals("sender")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.file_icon);
}else if(userType.equals("receiver")){
fileIcon = ContextCompat.getDrawable(this,R.drawable.file_icon_sender);
}
}
return fileIcon;
}
private String calculateFileSize(long fileSizeInBytes) {
return android.text.format.Formatter.formatShortFileSize(this,fileSizeInBytes);
}
private void openFile(String url,String fileType,String fileName) {
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
fileIntent.setDataAndType(Uri.parse(url),fileType);
fileIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(fileIntent);
}catch (ActivityNotFoundException e){
Toast.makeText(this,"Downloading File",Toast.LENGTH_SHORT).show();
downloadFile(url,fileName);
}
}
private void downloadFile(String url, String fileName) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading File...");
request.setTitle(fileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
}
if (manager != null) {
manager.enqueue(request);
}
}
@SuppressLint("SetTextI18n")
private void showDateOrNot(ChatHolder holder, ChatModel model) {
String todayDate = timeStampHandler.displayDate(new Timestamp(System.currentTimeMillis()).getTime());
if (model.isShow_date()){
if (model.getChat_date().equals(todayDate)){
holder.dateStampTextView.setText("Today");
}else {
holder.dateStampTextView.setText(model.getChat_date());
}
}else if(!model.isShow_date()){
holder.dateStampTextView.setVisibility(View.GONE);
}
if(model.isIs_seen() && emailId.equals(model.getFrom_uid())){
holder.seenStamp.setVisibility(View.VISIBLE);
}else {
holder.seenStamp.setVisibility(View.GONE);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.timeStampSenderText.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_END);
holder.timeStampSenderText.setLayoutParams(params);
}
}
private void setSeenStatus(FirestoreRecyclerAdapter<ChatModel, ChatHolder> adapter) {
String lastMsgFrom = adapter.getItem(adapter.getItemCount() - 1).getFrom_uid();
if (!emailId.equals(lastMsgFrom)){
CollectionReference collection = db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).collection(String.valueOf(FireStoreCollections.Messages));
collection.get().addOnCompleteListener(task -> {
if (task.isSuccessful()){
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())){
HashMap<String,Object> seenMap = new HashMap<>();
seenMap.put("is_seen",true);
collection.document(document.getId()).update(seenMap).addOnCompleteListener(task1 -> {
});
}
}
});
}
}
private void scrollToBottom(FirestoreRecyclerAdapter<ChatModel, ChatHolder> adapter) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeChanged(positionStart, itemCount);
int messageCount = adapter.getItemCount();
int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 || (positionStart >= (messageCount - 1) && lastVisiblePosition == (positionStart - 1))){
mChatsRecyclerView.smoothScrollToPosition(positionStart);
new Handler().postDelayed(() -> {
mChatsRecyclerView.setVisibility(View.VISIBLE);
mChatProgressDialog.dismiss();
}, 100);
}
}
});
}
private void resizeWindow() {
if (adapter != null){
if (adapter.getItemCount() >= 5){
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}else {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
}
}
private void sendMessage() {
String message = mSendMessageEditText.getText().toString();
if (!TextUtils.isEmpty(message)){
String messageId = String.valueOf((long) Math.floor(Math.random() * 9000000000000L) + 1000000000000L);
long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
msgTime = timeStampHandler.displayTimeStamp(timestamp);
msgDate = timeStampHandler.displayDate(timestamp);
Map<String,Object> chatMap = new HashMap<>();
chatMap.put("message_id", messageId);
chatMap.put("from_uid",emailId);
chatMap.put("message",message);
chatMap.put("timestamp", timestamp);
chatMap.put("chat_time",msgTime);
if (adapter.getItemCount() == 0){
chatMap.put("chat_date", msgDate);
chatMap.put("show_date", true);
}else if(adapter.getItemCount() != 0 && adapter.getItem(adapter.getItemCount() - 1).getChat_date().equals(msgDate)){
chatMap.put("show_date", false);
chatMap.put("chat_date",msgDate);
}else {
chatMap.put("show_date", true);
chatMap.put("chat_date",msgDate);
}
chatMap.put("image_message", "none");
chatMap.put("to_uid", chatting_with_uid);
chatMap.put("is_seen",false);
chatMap.put("file_message", "none");
mSendMessageEditText.setText("");
db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id)
.collection(String.valueOf(FireStoreCollections.Messages))
.document(messageId).set(chatMap).addOnCompleteListener(task -> {
if (task.isSuccessful()){
// We do not need the below method as scrollToBottom() method is
// taking care to scroll to the bottom of the screen after msg gets sent.
// mChatsRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
updateLastMessage(message,emailId,msgTime);
}
});
}
}
private void updateLastMessage(String message, String uid, String msgTime) {
HashMap<String,Object> updateLastMsgMap = new HashMap<>();
updateLastMsgMap.put("message",message);
updateLastMsgMap.put("from_uid",uid);
updateLastMsgMap.put("message_time",msgTime);
updateLastMsgMap.put("message_attachment","none");
db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).update(updateLastMsgMap);
}
private void sendImageAttachment() {
ImagePicker.Companion.with(this)
.compress(2048)
.maxResultSize(2040,2040)
.start(IMAGE_PICK_REQUEST_CODE);
}
private void sendFileAttachment() {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("application/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, FILE_PICK_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String messageId = String.valueOf((long) Math.floor(Math.random() * 9000000000000L) + 1000000000000L);
long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
msgTime = timeStampHandler.displayTimeStamp(timestamp);
msgDate = timeStampHandler.displayDate(timestamp);
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null){
switch (requestCode){
case IMAGE_PICK_REQUEST_CODE:
uploadImageAttachment(data,messageId,timestamp,msgTime,msgDate);
break;
case FILE_PICK_REQUEST_CODE:
uploadFileAttachment(data,messageId,timestamp,msgTime,msgDate);
break;
}
}
}
private void uploadImageAttachment(Intent data, String messageId, long timestamp, String msgTime, String msgDate) {
mProgressDialog.setMessage("Sending Image, Please wait...");
mProgressDialog.show();
mImageUri = Objects.requireNonNull(data).getData();
filePath = mAttachImageRef.child("chat_images").child(emailId + ".jpg");
filePath.putFile(mImageUri).addOnCompleteListener(task -> {
if (task.isSuccessful()){
mAttachImageRef.child("chat_images").child(emailId + ".jpg").getDownloadUrl().addOnSuccessListener(uri -> {
final String downloadUrl = uri.toString();
UploadTask uploadTask = filePath.putFile(mImageUri);
uploadTask.addOnSuccessListener(taskSnapshot -> {
if (task.isSuccessful()){
Map<String,Object> chatUserImageMap = new HashMap<>();
chatUserImageMap.put("message_id", messageId);
chatUserImageMap.put("from_uid",emailId);
chatUserImageMap.put("timestamp", timestamp);
chatUserImageMap.put("chat_time",msgTime);
if (adapter.getItemCount() == 0){
chatUserImageMap.put("chat_date", msgDate);
chatUserImageMap.put("show_date", true);
}else if(adapter.getItemCount() != 0 && adapter.getItem(adapter.getItemCount() - 1).getChat_date().equals(msgDate)){
chatUserImageMap.put("show_date", false);
chatUserImageMap.put("chat_date",msgDate);
}else {
chatUserImageMap.put("show_date", true);
chatUserImageMap.put("chat_date",msgDate);
}
chatUserImageMap.put("is_seen", false);
chatUserImageMap.put("image_message", downloadUrl);
chatUserImageMap.put("to_uid",chatting_with_uid);
chatUserImageMap.put("file_message","none");
db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).collection(String.valueOf(FireStoreCollections.Messages)).document(messageId).set(chatUserImageMap).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(this,"Image Sent Successfully", Toast.LENGTH_SHORT).show();
updateLastAttachmentMessage("Image",emailId,msgTime);
}
});
}
});
});
}
});
}
private void uploadFileAttachment(Intent data, String messageId, long timestamp, String msgTime, String msgDate) {
Cursor returnCursor = getContentResolver().query(data.getData(), null, null, null, null);
String fileType = getContentResolver().getType(data.getData());
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String fileName = returnCursor.getString(nameIndex);
if(!calculateFileSize(sizeIndex, returnCursor)){
Toast.makeText(this,"File size cannot be greater than 5MB",Toast.LENGTH_LONG).show();
}else {
mProgressDialog.setMessage("Uploading File, Please wait...");
mProgressDialog.show();
Uri fileUri = data.getData();
filePath = mAttachFileRef.child("chat_files").child(fileName);
filePath.putFile(fileUri).addOnCompleteListener(task -> {
if (task.isSuccessful()){
mAttachFileRef.child("chat_files").child(fileName).getDownloadUrl().addOnSuccessListener(uri -> {
final String downloadUrl = uri.toString();
UploadTask uploadTask = filePath.putFile(fileUri);
uploadTask.addOnSuccessListener(taskSnapshot -> {
if (task.isSuccessful()){
HashMap<String,Object> chatUserFileMap = new HashMap<>();
chatUserFileMap.put("message_id", messageId);
chatUserFileMap.put("from_uid",emailId);
chatUserFileMap.put("timestamp", timestamp);
chatUserFileMap.put("chat_time",msgTime);
if (adapter.getItemCount() == 0){
chatUserFileMap.put("chat_date", msgDate);
chatUserFileMap.put("show_date", true);
}else if(adapter.getItemCount() != 0 && adapter.getItem(adapter.getItemCount() - 1).getChat_date().equals(msgDate)){
chatUserFileMap.put("show_date", false);
chatUserFileMap.put("chat_date",msgDate);
}else {
chatUserFileMap.put("show_date", true);
chatUserFileMap.put("chat_date",msgDate);
}
chatUserFileMap.put("is_seen", false);
chatUserFileMap.put("image_message","none");
chatUserFileMap.put("file_message", downloadUrl);
chatUserFileMap.put("to_uid",chatting_with_uid);
chatUserFileMap.put("file_name",fileName);
chatUserFileMap.put("file_type",fileType);
chatUserFileMap.put("file_size_in_bytes", returnCursor.getLong(sizeIndex));
db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).collection(String.valueOf(FireStoreCollections.Messages)).document(messageId).set(chatUserFileMap).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
Toast.makeText(getApplicationContext(),"File Sent Successfully",Toast.LENGTH_SHORT).show();
returnCursor.close();
mProgressDialog.dismiss();
updateLastAttachmentMessage("File",emailId,msgTime);
}
});
}
});
});
}
});
}
}
private boolean calculateFileSize(int sizeIndex,Cursor returnCursor){
long sizeInKB = returnCursor.getLong(sizeIndex)/1024;
long sizeInMB = sizeInKB/1024;
int maxFileSize = 5; // 5MB
return sizeInMB <= maxFileSize;
}
private void updateLastAttachmentMessage(String attachmentType, String uid, String msgTime){
HashMap<String,Object> updateLastImgMsgMap = new HashMap<>();
updateLastImgMsgMap.put("message_attachment",attachmentType);
updateLastImgMsgMap.put("from_uid",uid);
updateLastImgMsgMap.put("message_time",msgTime);
updateLastImgMsgMap.put("message","none");
db.collection(String.valueOf(FireStoreCollections.ChatChannel)).document(chat_channel_id).update(updateLastImgMsgMap);
}
@SuppressLint("NonConstantResourceId")
public static class ChatHolder extends RecyclerView.ViewHolder {
@BindView(R.id.senderMessageView)
TextView senderMessage;
@BindView(R.id.receiverMessageView)
TextView receiverMessage;
@BindView(R.id.senderMessageContainer)
CardView senderMessageContainer;
@BindView(R.id.receiverMessageContainer)
CardView receiverMessageContainer;
@BindView(R.id.timestampSender)
TextView timeStampSenderText;
@BindView(R.id.timestampReceiver)
TextView timeStampReceiver;
@BindView(R.id.senderMessageImageContainer)
CardView senderMessageImageContainer;
@BindView(R.id.receiverImageContainer)
CardView receiverMessageImageContainer;
@BindView(R.id.senderImageAttach)
ImageView senderImageAttach;
@BindView(R.id.receiverImageAttach)
ImageView receiverImageAttach;
@BindView(R.id.dateStamp)
TextView dateStampTextView;
@BindView(R.id.seenStamp)
ImageView seenStamp;
@BindView(R.id.senderMessageFileContainer)
CardView senderFileContainer;
@BindView(R.id.receiverFileContainer)
CardView receiverFileContainer;
@BindView(R.id.fileNameSender)
TextView senderFileName;
@BindView(R.id.fileNameReceiver)
TextView receiverFileName;
@BindView(R.id.senderFileExtension)
TextView senderFileExtension;
@BindView(R.id.receiverFileExtension)
TextView receiverFileExtension;
@BindView(R.id.fileSizeSender)
TextView senderFileSize;
@BindView(R.id.fileSizeReceiver)
TextView receiverFileSize;
@BindView(R.id.fileIconSender)
ImageView fileIconSender;
@BindView(R.id.fileIconReceiver)
ImageView fileIconReceiver;
public ChatHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onResume() {
super.onResume();
mSendMessageEditText.setOnTouchListener((v, event) -> {
resizeWindow();
return false;
});
}
@Override
protected void onDestroy() {
adapter.stopListening();
listener.remove();
super.onDestroy();
}
}