Advertisement
kitlolz012

tourist hot chat

Nov 11th, 2023
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.01 KB | Source Code | 0 0
  1. package com.example.gypsy;
  2.  
  3. import androidx.annotation.NonNull;
  4. import androidx.appcompat.app.AppCompatActivity;
  5. import androidx.recyclerview.widget.LinearLayoutManager;
  6. import androidx.recyclerview.widget.RecyclerView;
  7.  
  8. import android.os.Bundle;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.widget.EditText;
  12. import android.widget.ImageButton;
  13. import android.widget.TextView;
  14.  
  15. import com.google.firebase.auth.FirebaseAuth;
  16. import com.google.firebase.auth.FirebaseUser;
  17. import com.google.firebase.database.ChildEventListener;
  18. import com.google.firebase.database.DataSnapshot;
  19. import com.google.firebase.database.DatabaseError;
  20. import com.google.firebase.database.DatabaseReference;
  21. import com.google.firebase.database.FirebaseDatabase;
  22. import com.google.firebase.database.ValueEventListener;
  23.  
  24. import java.text.SimpleDateFormat;
  25. import java.util.ArrayList;
  26. import java.util.Date;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Locale;
  30. import java.util.Map;
  31. import java.util.Objects;
  32. import java.util.UUID;
  33. import java.util.stream.Collectors;
  34. import java.util.stream.Stream;
  35.  
  36. public class TouristHotelChat extends AppCompatActivity {
  37.  
  38.     private RecyclerView messageRecyclerView;
  39.     private MessageAdapter messageAdapter;
  40.     private List<MessageModel> messageList;
  41.  
  42.     private EditText messageEditText;
  43.     private ImageButton sendButton;
  44.  
  45.     private DatabaseReference databaseReference;
  46.     private FirebaseUser currentUser;
  47.     private String recipientUserId;
  48.     private String chatRoomId;
  49.     private String currentUserName;
  50.     private String recipientUserName;
  51.     private String senderProfilePic;
  52.     private String recipientProfilePic;
  53.  
  54.     private TextView recipientNameTextView;
  55.  
  56.     private static final String TAG= "TouristHotelChat";
  57.  
  58.     @Override
  59.     protected void onCreate(Bundle savedInstanceState) {
  60.         super.onCreate(savedInstanceState);
  61.         setContentView(R.layout.activity_tourist_hotel_chat);
  62.  
  63.         databaseReference = FirebaseDatabase.getInstance().getReference();
  64.         currentUser = FirebaseAuth.getInstance().getCurrentUser();
  65.         recipientUserId = getIntent().getStringExtra("recipientUserId"); // nanggaling sa DynamicHotel at BookingDetail
  66.         recipientUserName = getIntent().getStringExtra("recipientUserName"); // nanggaling sa DynamicHotel at BookingDetail
  67.         currentUserName = getIntent().getStringExtra("currentUserName");
  68.  
  69.         Log.d(TAG, "Recipient recipient user ID: " + recipientUserId);
  70.         Log.d(TAG, "Recipient  Current user name: " + currentUserName);
  71.         Log.d(TAG, "Recipient recipient user name: " + recipientUserName);
  72.  
  73.         chatRoomId = generateUniqueChatRoomId(currentUser.getUid(), recipientUserId);
  74.         Log.d(TAG, "Generated Chat Room ID: " + chatRoomId);
  75.         createChatRoom(chatRoomId);
  76.  
  77.         messageRecyclerView = findViewById(R.id.messageRecyclerView);
  78.         LinearLayoutManager layoutManager = new LinearLayoutManager(this);
  79.         layoutManager.setStackFromEnd(true);
  80.         messageRecyclerView.setLayoutManager(layoutManager);
  81.  
  82.         messageList = new ArrayList<>();
  83.         messageAdapter = new MessageAdapter(messageList, currentUser.getUid());
  84.         messageRecyclerView.setAdapter(messageAdapter);
  85.  
  86.         messageEditText = findViewById(R.id.messageEditText);
  87.         sendButton = findViewById(R.id.sendButton);
  88.  
  89.         sendButton.setOnClickListener(new View.OnClickListener() {
  90.             @Override
  91.             public void onClick(View v) {
  92.                 sendMessage();
  93.             }
  94.         });
  95.  
  96.         listenForMessages(chatRoomId);
  97.  
  98.         DatabaseReference categoryRef = databaseReference.child("users");
  99.         categoryRef.addListenerForSingleValueEvent(new ValueEventListener() {
  100.             @Override
  101.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  102.                 if (dataSnapshot != null && dataSnapshot.exists()) {
  103.                     DataSnapshot hotelSnapshot = dataSnapshot.child("Hotel");
  104.                     DataSnapshot touristSnapshot = dataSnapshot.child("Tourist");
  105.                     DataSnapshot restaurantSnapshot = dataSnapshot.child("Restaurant");
  106.  
  107.                     if (recipientUserId != null) {
  108.                         if (hotelSnapshot != null && hotelSnapshot.exists() && hotelSnapshot.hasChild(recipientUserId)) {
  109.                             retrieveRecipientName("Hotel", recipientUserId);
  110.                         } else if (touristSnapshot != null && touristSnapshot.exists() && touristSnapshot.hasChild(recipientUserId)) {
  111.                             retrieveRecipientName("Tourist", recipientUserId);
  112.                         } else if (restaurantSnapshot != null && restaurantSnapshot.exists() && restaurantSnapshot.hasChild(recipientUserId)) {
  113.                             retrieveRecipientName("Restaurant", recipientUserId);
  114.                         }
  115.                     }
  116.                 }
  117.             }
  118.  
  119.  
  120.  
  121.  
  122.  
  123.             @Override
  124.             public void onCancelled(@NonNull DatabaseError databaseError) {
  125.             }
  126.         });
  127.     }
  128.  
  129.     private void sendMessage() {
  130.         String messageText = messageEditText.getText().toString().trim();
  131.         if (!messageText.isEmpty()) {
  132.             String messageId = generateId();
  133.             long timestamp = System.currentTimeMillis();
  134.  
  135.             MessageModel message = new MessageModel(messageText, currentUser.getUid(), recipientUserId, currentUserName, recipientUserName, messageId, timestamp, senderProfilePic, recipientProfilePic);
  136.  
  137.             String chatRoomPath = "chat_rooms/" + chatRoomId + "/messages";
  138.  
  139.             DatabaseReference chatRoomRef = databaseReference.child(chatRoomPath);
  140.             chatRoomRef.child(messageId).setValue(message);
  141.  
  142.             messageEditText.setText("");
  143.  
  144.             Log.d(TAG, "Sent Message:");
  145.             Log.d(TAG, "Message Text: " + messageText);
  146.             Log.d(TAG, "Message ID: " + messageId);
  147.             Log.d(TAG, "Sender ID: " + currentUser);
  148.         }
  149.     }
  150.     private void listenForMessages(String chatRoomId) {
  151.         String chatRoomPath = "chat_rooms/" + chatRoomId + "/messages";
  152.  
  153.         DatabaseReference chatRoomRef = databaseReference.child(chatRoomPath);
  154.         chatRoomRef.addChildEventListener(new ChildEventListener() {
  155.             @Override
  156.             public void onChildAdded(@NonNull DataSnapshot dataSnapshot, String s) {
  157.                 MessageModel message = dataSnapshot.getValue(MessageModel.class);
  158.                 if (message != null) {
  159.                     messageList.add(message);
  160.                     messageAdapter.notifyDataSetChanged();
  161.                     messageRecyclerView.scrollToPosition(messageList.size() - 1);
  162.                 }
  163.             }
  164.  
  165.             @Override
  166.             public void onChildChanged(@NonNull DataSnapshot dataSnapshot, String s) {
  167.             }
  168.  
  169.             @Override
  170.             public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
  171.             }
  172.  
  173.             @Override
  174.             public void onChildMoved(@NonNull DataSnapshot dataSnapshot, String s) {
  175.             }
  176.  
  177.             @Override
  178.             public void onCancelled(@NonNull DatabaseError databaseError) {
  179.             }
  180.         });
  181.     }
  182.     private String generateUniqueChatRoomId(String senderId, String receiverId) {
  183.         senderId = (senderId != null) ? senderId : "";
  184.         receiverId = (receiverId != null) ? receiverId : "";
  185.  
  186.         String sortedUserIds = Stream.of(senderId, receiverId)
  187.                 .filter(Objects::nonNull)
  188.                 .sorted()
  189.                 .collect(Collectors.joining("_"));
  190.  
  191.         return "chat_" + sortedUserIds;
  192.     }
  193.     private void createChatRoom(String chatRoomId) {
  194.         String chatRoomPath = "chat_rooms/" + chatRoomId;
  195.         DatabaseReference chatRoomRef = databaseReference.child(chatRoomPath);
  196.  
  197.         chatRoomRef.addListenerForSingleValueEvent(new ValueEventListener() {
  198.             @Override
  199.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  200.                 if (currentUser != null && recipientUserId != null && !dataSnapshot.exists()) {
  201.                     Map<String, Object> participants = new HashMap<>();
  202.                     participants.put(currentUser.getUid(), true);
  203.                     participants.put(recipientUserId, true);
  204.  
  205.                     Map<String, Object> chatRoom = new HashMap<>();
  206.                     chatRoom.put("participants", participants);
  207.  
  208.                     chatRoomRef.setValue(chatRoom);
  209.                 }
  210.             }
  211.  
  212.             @Override
  213.             public void onCancelled(@NonNull DatabaseError databaseError) {
  214.             }
  215.         });
  216.     }
  217.     private String generateId() {
  218.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
  219.         Date currentDate = new Date();
  220.         return "message_" + dateFormat.format(currentDate);
  221.     }
  222.     private void retrieveRecipientName(String category, String userId) {
  223.         String recipientNamePath = "users/" + category + "/" + userId + "/name";
  224.         DatabaseReference recipientNameRef = databaseReference.child(recipientNamePath);
  225.  
  226.         recipientNameRef.addListenerForSingleValueEvent(new ValueEventListener() {
  227.             @Override
  228.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  229.                 Log.d("TouristHotelChat", "onDatachange called ");
  230.                 if (dataSnapshot.exists()) {
  231.                     String recipientName = dataSnapshot.getValue(String.class);
  232.                     TextView recipientNameTextView = findViewById(R.id.recipientNameTextView);
  233.                     recipientNameTextView.setText(recipientName);
  234.  
  235.                     Log.d("TouristHotelChat", "recipientName: " + recipientName);
  236.                 }
  237.             }
  238.             @Override
  239.             public void onCancelled(@NonNull DatabaseError databaseError) {
  240.             }
  241.         });
  242.     }
  243.  
  244.     public void goBack(View view) {
  245.         onBackPressed();
  246.     }
  247.  
  248.  
  249. }
  250.  
Tags: androud
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement