Advertisement
kitlolz012

EdithotelActivity(XML and java code )

Nov 17th, 2023
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 46.04 KB | Source Code | 0 0
  1. EditHotelActivity Java Code :
  2.  
  3. package com.example.gypsy;
  4.  
  5. import static android.content.ContentValues.TAG;
  6.  
  7. import android.app.Activity;
  8. import android.content.Intent;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import android.provider.MediaStore;
  12. import android.util.Log;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.ImageView;
  16. import android.widget.LinearLayout;
  17.  
  18. import com.google.android.material.textfield.TextInputEditText;
  19.  
  20.  
  21. import androidx.activity.result.ActivityResultLauncher;
  22. import androidx.activity.result.contract.ActivityResultContracts;
  23. import androidx.annotation.NonNull;
  24. import androidx.appcompat.app.AppCompatActivity;
  25. import androidx.core.content.ContextCompat;
  26. import androidx.fragment.app.FragmentManager;
  27. import androidx.fragment.app.FragmentTransaction;
  28. import androidx.recyclerview.widget.LinearLayoutManager;
  29. import androidx.recyclerview.widget.RecyclerView;
  30. import androidx.viewpager2.widget.ViewPager2;
  31.  
  32. import com.google.android.gms.tasks.OnCompleteListener;
  33. import com.google.android.gms.tasks.OnFailureListener;
  34. import com.google.android.gms.tasks.Task;
  35. import com.google.android.material.floatingactionbutton.FloatingActionButton;
  36. import com.google.android.material.textfield.TextInputEditText;
  37. import com.google.firebase.auth.FirebaseAuth;
  38. import com.google.firebase.auth.FirebaseUser;
  39. import com.google.firebase.database.DataSnapshot;
  40. import com.google.firebase.database.DatabaseError;
  41. import com.google.firebase.database.DatabaseReference;
  42. import com.google.firebase.database.FirebaseDatabase;
  43. import com.google.firebase.database.Query;
  44. import com.google.firebase.database.ValueEventListener;
  45. import com.google.firebase.storage.FirebaseStorage;
  46. import com.google.firebase.storage.StorageReference;
  47. import com.google.firebase.storage.UploadTask;
  48. import java.util.ArrayList;
  49. import java.util.HashMap;
  50. import java.util.List;
  51. import java.util.Map;
  52. import java.util.concurrent.atomic.AtomicInteger;
  53.  
  54. public class EditHotelActivity extends AppCompatActivity {
  55.  
  56.     private List<Uri> imageUris = new ArrayList<>();
  57.     private ActivityResultLauncher<Intent> galleryLauncher;
  58.     private FloatingActionButton uploadButton;
  59.     private TextInputEditText hotelNameET;
  60.     private TextInputEditText hotelAddET;
  61.     private TextInputEditText hotelDescET;
  62.     private TextInputEditText hotelContactET;
  63.     private TextInputEditText hotelEmailET;
  64.     private TextInputEditText roomTypeET;
  65.     private List<String> roomTypes = new ArrayList<>();
  66.     private RoomTypeAdapter roomTypeAdapter;
  67.     private RecyclerView roomTypeRecyclerView;
  68.     private TextInputEditText cancellationPolicyET;
  69.     private TextInputEditText amenityET;
  70.     private TextInputEditText gcashNumberET;
  71.     private TextInputEditText gcashNameET;
  72.     private Button postButton, cancelButton;
  73.     private Uri imageUri;
  74.     private StorageReference storageReference;
  75.     private DatabaseReference databaseReference;
  76.     private String userId;
  77.     private HotelImageSliderAdapter adapter;
  78.     private ViewPager2 viewPager;
  79.     private LinearLayout dotsLayout;
  80.     private ImageView[] dots;
  81.  
  82.  
  83.  
  84.     @Override
  85.     protected void onCreate(Bundle savedInstanceState) {
  86.         super.onCreate(savedInstanceState);
  87.         setContentView(R.layout.activity_edit_hotel);
  88.  
  89.         viewPager = findViewById(R.id.viewPager);
  90.         dotsLayout = findViewById(R.id.dotsLayout);
  91.         uploadButton = findViewById(R.id.uploadButton);
  92.         hotelNameET = findViewById(R.id.hotelNameET);
  93.         hotelAddET = findViewById(R.id.hotelAddET);
  94.         hotelDescET = findViewById(R.id.hotelDescET);
  95.         hotelContactET = findViewById(R.id.hotelContactET);
  96.         hotelEmailET = findViewById(R.id.hotelEmailET);
  97.         roomTypeET = findViewById(R.id.roomtypeET);
  98.         amenityET = findViewById(R.id.amenityET);
  99.         cancellationPolicyET = findViewById(R.id.cancellationPolicyET);
  100.         gcashNumberET = findViewById(R.id.gcashNumber);
  101.         gcashNameET = findViewById(R.id.gcashName);
  102.         postButton = findViewById(R.id.postButton);
  103.         cancelButton = findViewById(R.id.cancelButton);
  104.  
  105.         TextInputEditText latitudeET = findViewById(R.id.latitudeET);
  106.         TextInputEditText longitudeET = findViewById(R.id.longitudeET);
  107.  
  108.  
  109.  
  110.         roomTypeRecyclerView = findViewById(R.id.roomTypesRecyclerView);
  111.         roomTypeAdapter = new RoomTypeAdapter(roomTypes, new RoomTypeAdapter.OnRoomTypeDeleteListener() {
  112.             @Override
  113.             public void deleteRoomType(String roomType) {
  114.                     getHotelId(new HotelIdCallback() {
  115.                         @Override
  116.                         public void onHotelIdReceived(String hotelId) {
  117.                             if (hotelId != null) {
  118.                                 DatabaseReference hotelRef = databaseReference.child("hotels").child(hotelId);
  119.  
  120.                                 // Fetch the current room types
  121.                                 hotelRef.child("roomTypes").addListenerForSingleValueEvent(new ValueEventListener() {
  122.                                     @Override
  123.                                     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  124.                                         if (dataSnapshot.exists()) {
  125.                                             List<String> currentRoomTypes = new ArrayList<>();
  126.  
  127.                                             for (DataSnapshot roomTypeSnapshot : dataSnapshot.getChildren()) {
  128.                                                 String existingRoomType = roomTypeSnapshot.getValue(String.class);
  129.                                                 if (!roomType.equals(existingRoomType)) {
  130.                                                     currentRoomTypes.add(existingRoomType);
  131.                                                 }
  132.                                             }
  133.  
  134.                                             // Update the room types in the Firebase Realtime Database
  135.                                             updateRoomTypesInDatabase(hotelRef, currentRoomTypes);
  136.                                         }
  137.                                     }
  138.  
  139.                                     @Override
  140.                                     public void onCancelled(@NonNull DatabaseError databaseError) {
  141.                                         Log.e("deleteRoomType", "Error: " + databaseError.getMessage());
  142.                                     }
  143.                                 });
  144.                             } else {
  145.                                 Log.e("deleteRoomType", "Hotel ID is null");
  146.                             }
  147.                         }
  148.                     });
  149.             }
  150.         });
  151.  
  152.  
  153.         roomTypeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
  154.         roomTypeRecyclerView.setAdapter(roomTypeAdapter);
  155.  
  156.         roomTypeET = findViewById(R.id.roomtypeET);
  157.         Button addRoomTypeBtn = findViewById(R.id.addRoomTypeBtn);
  158.  
  159.         // dynamically pag-add ng room types nila
  160.         addRoomTypeBtn.setOnClickListener(v -> {
  161.             String roomType = roomTypeET.getText().toString().trim();
  162.             if (!roomType.isEmpty()) {
  163.                 roomTypes.add(roomType);
  164.                 roomTypeAdapter.notifyDataSetChanged();
  165.                 roomTypeET.setText("");
  166.             }
  167.         });
  168.  
  169.         FirebaseAuth auth = FirebaseAuth.getInstance();
  170.         FirebaseUser currentUser = auth.getCurrentUser();
  171.         userId = currentUser.getUid();
  172.  
  173.         FirebaseStorage storage = FirebaseStorage.getInstance();
  174.         storageReference = storage.getReference();
  175.         FirebaseDatabase database = FirebaseDatabase.getInstance();
  176.         databaseReference = database.getReference();
  177.  
  178.         // adapter para sa multiple images ng hotel, slider
  179.         adapter = new HotelImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  180.         viewPager.setAdapter(adapter);
  181.  
  182.         // yung dots nag-iindicate ng pang ilang images na, parang sa ig
  183.         dotsLayout = findViewById(R.id.dotsLayout);
  184.         HotelImageSliderAdapter adapter = new HotelImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  185.         viewPager.setAdapter(adapter);
  186.  
  187.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  188.             @Override
  189.             public void onPageSelected(int position) {
  190.                 super.onPageSelected(position);
  191.                 adapter.updateDotsIndicator(position);
  192.             }
  193.         });
  194.  
  195.         adapter.updateDotsIndicator(0);
  196.  
  197.         // gallery
  198.         galleryLauncher = registerForActivityResult(
  199.                 new ActivityResultContracts.StartActivityForResult(),
  200.                 result -> {
  201.                     if (result.getResultCode() == Activity.RESULT_OK) {
  202.                         Intent data = result.getData();
  203.                         if (data != null && data.getData() != null) {
  204.                             imageUri = data.getData();
  205.                             imageUris.add(imageUri);
  206.  
  207.                             adapter.notifyDataSetChanged();
  208.                         }
  209.                     }
  210.                 }
  211.         );
  212.  
  213.         uploadButton.setOnClickListener(v -> openGallery());
  214.  
  215.         // button "save changes" mapopost na sa tourist interface
  216.         postButton.setOnClickListener(v -> {
  217.             String hotelName = hotelNameET.getText().toString();
  218.             String hotelAddress = hotelAddET.getText().toString();
  219.             String hotelDescription = hotelDescET.getText().toString();
  220.             String hotelContact = hotelContactET.getText().toString();
  221.             String hotelEmail = hotelEmailET.getText().toString();
  222.             String roomType = roomTypeET.getText().toString();
  223.             String cancellationPolicy = cancellationPolicyET.getText().toString();
  224.             String amenitiesHotel = amenityET.getText().toString();
  225.             String gcashNumber = gcashNumberET.getText().toString();
  226.             String gcashName = gcashNameET.getText().toString();
  227.  
  228.             String latitude = latitudeET.getText().toString(); // Get latitude
  229.             String longitude = longitudeET.getText().toString(); // Get longitude
  230.  
  231.             checkIfExists(userId, hotelName, hotelAddress, hotelDescription, hotelContact, hotelEmail, roomTypes,
  232.                     cancellationPolicy, imageUri, amenitiesHotel, gcashNumber, gcashName, Double.parseDouble(latitude), Double.parseDouble(longitude));
  233.  
  234.  
  235.             // back to HotelEditFrag, or yung read-only, na nakaretrieve na
  236.             Intent intent = new Intent(this, MainActivity2.class);
  237.             intent.putExtra("fragmentToLoad", "HotelEditFragment");
  238.             startActivity(intent);
  239.         });
  240.  
  241.  
  242.         retrieve(userId);
  243.  
  244.         cancelButton.setOnClickListener(v -> {
  245.             HotelEditFragment hotelEditFragment = new HotelEditFragment();
  246.  
  247.             FragmentManager fragmentManager = getSupportFragmentManager();
  248.             FragmentTransaction transaction = fragmentManager.beginTransaction();
  249.             transaction.replace(R.id.container, hotelEditFragment);
  250.             transaction.addToBackStack(null);
  251.             transaction.commit();
  252.         });
  253.  
  254.  
  255.         addDotsIndicator(0); // para lang to sa dots sa image slider
  256.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  257.             @Override
  258.             public void onPageSelected(int position) {
  259.                 super.onPageSelected(position);
  260.                 addDotsIndicator(position);
  261.             }
  262.         });
  263.  
  264.         Log.d(TAG, "image upload triggeredd");
  265.     }
  266.  
  267.     // if nag eexist na yung user sa "hotels", di na pwede mag generate ng new set of data, para iwas doble doeble
  268.     private void checkIfExists(String userId, String hotelName, String hotelAddress, String hotelDescription,
  269.                                String hotelContact, String hotelEmail, List<String> roomTypes,
  270.                                String cancellationPolicy, Uri imageUri, String amenitiesHotel,
  271.                                String gcashNumber, String gcashName, double latitude, double longitude) {
  272.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  273.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  274.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  275.             @Override
  276.             // pag nag-eexist na, mag uupdate nalang yung existing data instead na gumawa ng new
  277.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  278.                 if (dataSnapshot.exists()) {
  279.                     String existingHotelId = dataSnapshot.getChildren().iterator().next().getKey();
  280.                     update(hotelName, hotelAddress, hotelDescription, imageUris, hotelContact, hotelEmail, roomTypes,
  281.                             cancellationPolicy, existingHotelId, amenitiesHotel, gcashNumber, gcashName, latitude, longitude);
  282.                     adapter.setUris(imageUris);
  283.                     adapter.notifyDataSetChanged();
  284.                     Log.d(TAG, "hotel exists, id: " + userId);
  285.                 } else {
  286.                     // if hindi pa nag-eeexist, gagawa ng new data under "hotels"
  287.                     create(userId, hotelName, hotelAddress, hotelDescription, hotelContact, hotelEmail, roomTypes,
  288.                             cancellationPolicy, imageUris, amenitiesHotel, gcashNumber, gcashName, latitude, longitude);
  289.                     adapter.setUris(imageUris);
  290.                     adapter.notifyDataSetChanged();
  291.                     Log.d(TAG, "hotel dont exist: .getText().getText() " + userId);
  292.                 }
  293.             }
  294.  
  295.             @Override
  296.             public void onCancelled(@NonNull DatabaseError databaseError) {
  297.                 Log.e("check", "error" + databaseError.getMessage());
  298.             }
  299.         });
  300.     }
  301.  
  302.     private void create(String userId, String hotelName, String hotelAddress, String hotelDescription, String hotelContact, String hotelEmail,
  303.                         List<String> roomTypes, String cancellationPolicy, List<Uri> imageUris, String amenitiesHotel, String gcashNumber,
  304.                         String gcashName, double latitude, double longitude) {
  305.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  306.  
  307.         DatabaseReference hotelRef = hotelsRef.push();
  308.         String hotelId = hotelRef.getKey();
  309.  
  310.         List<String> imageUrls = new ArrayList<>();
  311.         AtomicInteger uploadCount = new AtomicInteger(0);
  312.  
  313.         for (int i = 0; i < imageUris.size(); i++) {
  314.             final int finalIndex = i;
  315.             Uri imageUri = imageUris.get(i);
  316.             StorageReference imageRef = storageReference.child("hotel_images/" + hotelId + "/image" + (i + 1));
  317.             Log.d(TAG, "Image Storage Reference: " + imageRef.toString());
  318.             UploadTask uploadTask = imageRef.putFile(imageUri);
  319.  
  320.             uploadTask.addOnFailureListener(new MyFailureListener());
  321.             uploadTask.addOnSuccessListener(taskSnapshot -> {
  322.  
  323.                 imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
  324.                     @Override
  325.                     public void onComplete(@NonNull Task<Uri> task) {
  326.                         String url = "https://" + task.getResult().getEncodedAuthority() + task.getResult().getEncodedPath() + "?alt=media&token=" + task.getResult().getQueryParameters("token").get(0);
  327.                         imageUrls.add(url);
  328.  
  329.                         if (uploadCount.incrementAndGet() == imageUris.size()) {
  330.                             save(hotelId, imageUrls, hotelName, hotelAddress, hotelDescription, hotelContact,
  331.                                     hotelEmail, roomTypes, cancellationPolicy, amenitiesHotel, gcashNumber, gcashName, latitude,longitude);
  332.  
  333.                             adapter.setUris(imageUris);
  334.                             adapter.notifyDataSetChanged();
  335.                         }
  336.                     }
  337.                 });
  338.             }).addOnFailureListener(e -> {
  339.                 Log.e(TAG, "failed image uploadnumber: " + (finalIndex + 1) + ": " + e.getMessage());
  340.             });
  341.         }
  342.     }
  343.  
  344.     private void update(String hotelName, String hotelAddress, String hotelDescription, List<Uri> imageUris, String hotelContact,
  345.                         String hotelEmail, List<String> roomTypes, String cancellationPolicy, String hotelId, String amenitiesHotel,
  346.                         String gcashNumber, String gcashName, double latitude, double longitude) {
  347.  
  348.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  349.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  350.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  351.             @Override
  352.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  353.                 if (dataSnapshot.exists()) {
  354.                     for (com.google.firebase.database.DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
  355.                         String hotelId = childSnapshot.getKey();
  356.  
  357.                         DatabaseReference hotelRef = hotelsRef.child(hotelId);
  358.                         hotelRef.child("name").setValue(hotelName);
  359.                         hotelRef.child("address").setValue(hotelAddress);
  360.                         hotelRef.child("description").setValue(hotelDescription);
  361.                         hotelRef.child("contact").setValue(hotelContact);
  362.                         hotelRef.child("email").setValue(hotelEmail);
  363.                         hotelRef.child("cancellationPolicy").setValue(cancellationPolicy);
  364.                         hotelRef.child("amenities").setValue(amenitiesHotel);
  365.                         hotelRef.child("gcashNumber").setValue(gcashNumber);
  366.                         hotelRef.child("gcashName").setValue(gcashName);
  367.  
  368.                         hotelRef.child("latitude").setValue(latitude); // Add this line for latitude
  369.                         hotelRef.child("longitude").setValue(longitude); // Add this line for longitude
  370.  
  371.  
  372.                         saveRoomTypes(hotelId, roomTypes);
  373.  
  374.  
  375.                         hotelRef.child("images").removeValue();
  376.  
  377.                         StorageReference imagesStorageRef = storageReference.child("hotel_images/" + hotelId);
  378.                         imagesStorageRef.listAll().addOnSuccessListener(listResult -> {
  379.                             for (StorageReference item : listResult.getItems()) {
  380.                                 item.delete().addOnSuccessListener(aVoid -> {
  381.                                     Log.d(TAG, "Deleted file: " + item.getName());
  382.  
  383.                                     if (!imageUris.isEmpty()) {
  384.                                         List<String> imageUrls = new ArrayList<>();
  385.                                         AtomicInteger uploadCount = new AtomicInteger(0);
  386.  
  387.                                         for (int i = 0; i < imageUris.size(); i++) {
  388.                                             Uri imageUri = imageUris.get(i);
  389.                                             if (imageUri != null) {
  390.                                                 StorageReference imageRef = storageReference.child("hotel_images/" + hotelId + "/image" + (i + 1));
  391.                                                 UploadTask uploadTask = imageRef.putFile(imageUri);
  392.  
  393.                                                 uploadTask.addOnSuccessListener(taskSnapshot -> {
  394.                                                     imageRef.getDownloadUrl().addOnSuccessListener(downloadUri -> {
  395.                                                         String imageUrl = downloadUri.toString();
  396.                                                         imageUrls.add(imageUrl);
  397.  
  398.                                                         if (uploadCount.incrementAndGet() == imageUris.size()) {
  399.                                                             // All images uploaded, update the database
  400.                                                             save(hotelId, imageUrls, hotelName, hotelAddress, hotelDescription, hotelContact,
  401.                                                                     hotelEmail, roomTypes, cancellationPolicy, amenitiesHotel, gcashNumber, gcashName,latitude,longitude);
  402.                                                         }
  403.                                                     }).addOnFailureListener(e -> {
  404.                                                         Log.e("image upload", "Firebase Storage Error: " + e.getMessage());
  405.                                                     });
  406.                                                 });
  407.                                                 uploadTask.addOnFailureListener(new OnFailureListener() {
  408.                                                     @Override
  409.                                                     public void onFailure(@NonNull Exception e) {
  410.                                                         Log.e("image upload", "Error during upload: " + e.getMessage());
  411.                                                     }
  412.                                                 });
  413.  
  414.                                                 uploadTask.addOnFailureListener(new MyFailureListener());
  415.                                             } else {
  416.                                                 Log.e(TAG, "ImageUri is null. Handle this case accordingly.");
  417.                                             }
  418.                                         }
  419.                                     }
  420.  
  421.                                 }).addOnFailureListener(exception -> {
  422.                                     Log.e(TAG, "Error deleting file: " + item.getName() + ", " + exception.getMessage());
  423.                                 });
  424.                             }
  425.                         });
  426.  
  427.  
  428.                     }
  429.                 }
  430.             }
  431.  
  432.             @Override
  433.             public void onCancelled(@NonNull DatabaseError databaseError) {
  434.                 Log.e("update", "error" + databaseError.getMessage());
  435.             }
  436.         });
  437.     }
  438.  
  439.     private void openGallery() {
  440.         // lalagyan natin to ng permission first
  441.         Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  442.         galleryLauncher.launch(galleryIntent);
  443.     }
  444.  
  445.     // always save changes
  446.     private void save(String hotelId, List<String> imageUrls, String hotelName, String hotelAddress, String hotelDescription,
  447.                       String hotelContact, String hotelEmail, List<String> roomTypes, String cancellationPolicy,
  448.                       String amenitiesHotel, String gcashNumber, String gcashName, double latitude, double longitude) {
  449.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  450.         DatabaseReference hotelRef = hotelsRef.child(hotelId);
  451.  
  452.         // set sa rdb yung value
  453.         hotelRef.child("name").setValue(hotelName);
  454.         hotelRef.child("address").setValue(hotelAddress);
  455.         hotelRef.child("description").setValue(hotelDescription);
  456.         hotelRef.child("contact").setValue(hotelContact);
  457.         hotelRef.child("email").setValue(hotelEmail);
  458.         hotelRef.child("cancellationPolicy").setValue(cancellationPolicy);
  459.         hotelRef.child("user_id").setValue(userId);
  460.         hotelRef.child("amenities").setValue(amenitiesHotel);
  461.         hotelRef.child("gcashNumber").setValue(gcashNumber);
  462.         hotelRef.child("gcashName").setValue(gcashName);
  463.  
  464.         hotelRef.child("latitude").setValue(latitude); // Add this line for latitude
  465.         hotelRef.child("longitude").setValue(longitude);
  466.  
  467.         Map<String, Object> imagesMap = new HashMap<>();
  468.         for (int i = 0; i < imageUrls.size(); i++) {
  469.             imagesMap.put("image" + (i + 1), imageUrls.get(i));
  470.         }
  471.         hotelRef.child("images").setValue(imagesMap);
  472.  
  473.         Map<String, Object> roomTypesMap = new HashMap<>();
  474.         for (int i = 0; i < roomTypes.size(); i++) {
  475.             roomTypesMap.put("roomType" + (i + 1), roomTypes.get(i));
  476.         }
  477.         hotelRef.child("roomTypes").setValue(roomTypesMap);
  478.     }
  479.  
  480.     // then reretrieve natin sa mga edit texts
  481.     private void retrieve(String userId) {
  482.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  483.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  484.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  485.             @Override
  486.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  487.                 if (dataSnapshot.exists()) {
  488.                     DataSnapshot hotelSnapshot = dataSnapshot.getChildren().iterator().next();
  489.  
  490.                     String title = hotelSnapshot.child("name").getValue(String.class);
  491.                     String hotelAddress = hotelSnapshot.child("address").getValue(String.class);
  492.                     String description = hotelSnapshot.child("description").getValue(String.class);
  493.                     String hotelContact = hotelSnapshot.child("contact").getValue(String.class);
  494.                     String hotelEmail = hotelSnapshot.child("email").getValue(String.class);
  495.                     String cancellationPolicy = hotelSnapshot.child("cancellationPolicy").getValue(String.class);
  496.                     String amenitiesHotel = hotelSnapshot.child("amenities").getValue(String.class);
  497.                     String gcashNumber = hotelSnapshot.child("gcashNumber").getValue(String.class);
  498.                     String gcashName = hotelSnapshot.child("gcashName").getValue(String.class);
  499.  
  500.                     Double latitudeDouble = hotelSnapshot.child("latitude").getValue(Double.class);
  501.                     Double longitudeDouble = hotelSnapshot.child("longitude").getValue(Double.class);
  502.  
  503. // Check for null before invoking toString()
  504.                     String latitude = (latitudeDouble != null) ? latitudeDouble.toString() : "defaultLatitude";
  505.                     String longitude = (longitudeDouble != null) ? longitudeDouble.toString() : "defaultLongitude";
  506.  
  507.  
  508.                     Log.d(TAG, "Retrieved Latitude: " + latitude);
  509.                     Log.d(TAG, "Retrieved Longitude: " + longitude);
  510.  
  511.  
  512.  
  513.  
  514.                     DataSnapshot roomTypesSnapshot = hotelSnapshot.child("roomTypes");
  515.                     List<String> roomTypes = new ArrayList<>();
  516.                     for (DataSnapshot roomTypeSnapshot : roomTypesSnapshot.getChildren()) {
  517.                         String roomType = roomTypeSnapshot.getValue(String.class);
  518.                         roomTypes.add(roomType);
  519.                     }
  520.  
  521.                     List<String> imageUrls = new ArrayList<>();
  522.                     DataSnapshot imagesSnapshot = hotelSnapshot.child("images");
  523.                     for (DataSnapshot imageSnapshot : imagesSnapshot.getChildren()) {
  524.                         String imageUrl = imageSnapshot.getValue(String.class);
  525.                         imageUrls.add(imageUrl);
  526.                     }
  527.  
  528.                     hotelNameET.setText(title);
  529.                     hotelDescET.setText(description);
  530.                     hotelAddET.setText(hotelAddress);
  531.                     hotelContactET.setText(hotelContact);
  532.                     hotelEmailET.setText(hotelEmail);
  533.                     cancellationPolicyET.setText(cancellationPolicy);
  534.                     amenityET.setText(amenitiesHotel);
  535.                     gcashNumberET.setText(gcashNumber);
  536.                     gcashNameET.setText(gcashName);
  537.  
  538.                     TextInputEditText latitudeET = findViewById(R.id.latitudeET);
  539.                     TextInputEditText longitudeET = findViewById(R.id.longitudeET);
  540.  
  541.                     latitudeET.setText(String.valueOf(latitude));
  542.                     longitudeET.setText(String.valueOf(longitude));
  543.  
  544.                     for (String imageUrl : imageUrls) {
  545.                         imageUris.add(Uri.parse(imageUrl));
  546.                     }
  547.  
  548.                     adapter.setUris(imageUris);
  549.                     adapter.notifyDataSetChanged();
  550.  
  551.                     roomTypeAdapter.setRoomTypes(roomTypes);
  552.                     roomTypeAdapter.notifyDataSetChanged();
  553.                 }
  554.             }
  555.  
  556.             @Override
  557.             public void onCancelled(@NonNull DatabaseError databaseError) {
  558.                 Log.e("retrieve", "error" + databaseError.getMessage());
  559.             }
  560.         });
  561.     }
  562.  
  563.     private void addDotsIndicator(int position) { // again for dots lang nung image slider
  564.         dots = new ImageView[imageUris.size()];
  565.         dotsLayout.removeAllViews();
  566.  
  567.         for (int i = 0; i < dots.length; i++) {
  568.             dots[i] = new ImageView(this);
  569.             dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_unselected));
  570.  
  571.             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
  572.                     LinearLayout.LayoutParams.WRAP_CONTENT,
  573.                     LinearLayout.LayoutParams.WRAP_CONTENT
  574.             );
  575.  
  576.             params.setMargins(8, 0, 8, 0);
  577.             dotsLayout.addView(dots[i], params);
  578.         }
  579.         if (dots.length > 0) {
  580.             dots[position].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_selected));
  581.         }
  582.     }
  583.  
  584.  
  585.     private void saveRoomTypes(String hotelId, List<String> roomTypes) {
  586.         DatabaseReference roomTypesRef = databaseReference.child("hotels").child(hotelId).child("roomTypes");
  587.  
  588.         if (roomTypes != null) {
  589.             for (int i = 0; i < roomTypes.size(); i++) {
  590.                 String roomType = roomTypes.get(i);
  591.                 if (roomType != null) {
  592.                     roomTypesRef.child("roomType" + (i + 1)).setValue(roomType);
  593.                 }
  594.             }
  595.         }
  596.     }
  597.  
  598.     private void deleteRoomType(String roomType) {
  599.         getHotelId(new HotelIdCallback() {
  600.             @Override
  601.             public void onHotelIdReceived(String hotelId) {
  602.                 if (hotelId != null) {
  603.                     DatabaseReference hotelRef = databaseReference.child("hotels").child(hotelId);
  604.  
  605.                     // Fetch the current room types
  606.                     hotelRef.child("roomTypes").addListenerForSingleValueEvent(new ValueEventListener() {
  607.                         @Override
  608.                         public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  609.                             if (dataSnapshot.exists()) {
  610.                                 List<String> currentRoomTypes = new ArrayList<>();
  611.  
  612.                                 for (DataSnapshot roomTypeSnapshot : dataSnapshot.getChildren()) {
  613.                                     String existingRoomType = roomTypeSnapshot.getValue(String.class);
  614.                                     if (!roomType.equals(existingRoomType)) {
  615.                                         currentRoomTypes.add(existingRoomType);
  616.                                     }
  617.                                 }
  618.  
  619.                                 // Update the room types in the Firebase Realtime Database
  620.                                 updateRoomTypesInDatabase(hotelRef, currentRoomTypes);
  621.                             }
  622.                         }
  623.  
  624.                         @Override
  625.                         public void onCancelled(@NonNull DatabaseError databaseError) {
  626.                             Log.e("deleteRoomType", "Error: " + databaseError.getMessage());
  627.                         }
  628.                     });
  629.                 } else {
  630.                     Log.e("deleteRoomType", "Hotel ID is null");
  631.                 }
  632.             }
  633.         });
  634.     }
  635.  
  636.     private void updateRoomTypesInDatabase(DatabaseReference hotelRef, List<String> roomTypes) {
  637.         // Set the updated room types in the database
  638.         hotelRef.child("roomTypes").removeValue(); // Remove the old room types
  639.  
  640.         Map<String, Object> roomTypesMap = new HashMap<>();
  641.         for (int i = 0; i < roomTypes.size(); i++) {
  642.             roomTypesMap.put("roomType" + (i + 1), roomTypes.get(i));
  643.         }
  644.         hotelRef.child("roomTypes").updateChildren(roomTypesMap);
  645.     }
  646.  
  647.     private void getHotelId(HotelIdCallback callback) {
  648.         FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
  649.         if (currentUser != null) {
  650.             String currentUserId = currentUser.getUid();
  651.  
  652.             DatabaseReference hotelRef = FirebaseDatabase.getInstance().getReference("hotels");
  653.             Query query = hotelRef.orderByChild("user_id").equalTo(currentUserId);
  654.  
  655.             query.addListenerForSingleValueEvent(new ValueEventListener() {
  656.                 @Override
  657.                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  658.                     if (dataSnapshot.exists()) {
  659.                         String hotelId = dataSnapshot.getChildren().iterator().next().getKey();
  660.                         callback.onHotelIdReceived(hotelId);
  661.                     } else {
  662.                         callback.onHotelIdReceived(null);
  663.                     }
  664.                 }
  665.  
  666.                 @Override
  667.                 public void onCancelled(@NonNull DatabaseError databaseError) {
  668.                     // Handle errors or failures
  669.                 }
  670.             });
  671.         } else {
  672.             callback.onHotelIdReceived(null);
  673.         }
  674.     }
  675.  
  676.     private interface HotelIdCallback {
  677.         void onHotelIdReceived(String hotelId);
  678.     }
  679.  
  680.  
  681. }
  682.  
  683.  
  684. XML CODE :
  685.  
  686. <?xml version="1.0" encoding="utf-8"?>
  687. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  688.     android:layout_width="match_parent"
  689.     android:layout_height="match_parent"
  690.     xmlns:app="http://schemas.android.com/apk/res-auto"
  691.     android:background="@color/basecolor2"
  692.     xmlns:app1="http://schemas.android.com/tools"
  693.     android:fillViewport="true">
  694.  
  695.     <LinearLayout
  696.         android:layout_width="match_parent"
  697.         android:layout_height="wrap_content"
  698.         android:orientation="vertical"
  699.         android:padding="16dp">
  700.  
  701.         <androidx.viewpager2.widget.ViewPager2
  702.             android:id="@+id/viewPager"
  703.             android:layout_width="match_parent"
  704.             android:layout_height="300dp"
  705.             android:background="@drawable/image_placeholder"/>
  706.  
  707.         <LinearLayout
  708.             android:id="@+id/dotsLayout"
  709.             android:layout_width="match_parent"
  710.             android:layout_height="wrap_content"
  711.             android:gravity="center"
  712.             android:orientation="horizontal"/>
  713.  
  714.  
  715.         <com.google.android.material.floatingactionbutton.FloatingActionButton
  716.             android:id="@+id/uploadButton"
  717.             android:layout_width="wrap_content"
  718.             android:layout_height="wrap_content"
  719.             android:layout_gravity="end"
  720.             android:layout_marginRight="45dp"
  721.             android:backgroundTint="@color/contrastcolor2"
  722.             android:baselineAlignBottom="false"
  723.             android:clickable="true"
  724.             android:src="@drawable/add_photo"
  725.             app1:ignore="SpeakableTextPresentCheck"
  726.             app:fabSize="normal"
  727.             app:layout_anchor="@id/appbar" />
  728.  
  729.         <com.google.android.material.textfield.TextInputLayout
  730.             android:layout_width="match_parent"
  731.             android:layout_height="wrap_content"
  732.             android:layout_marginVertical="5dp"
  733.             android:hint="Company's Name">
  734.  
  735.             <com.google.android.material.textfield.TextInputEditText
  736.                 android:id="@+id/hotelNameET"
  737.                 android:layout_width="match_parent"
  738.                 android:layout_height="wrap_content"
  739.                 android:padding="20dp"
  740.                 android:textSize="18sp"
  741.                 android:inputType="text" />
  742.  
  743.         </com.google.android.material.textfield.TextInputLayout>
  744.  
  745.         <com.google.android.material.textfield.TextInputLayout
  746.             android:layout_width="match_parent"
  747.             android:layout_height="wrap_content"
  748.             android:layout_marginVertical="5dp"
  749.             android:hint="Location">
  750.  
  751.             <com.google.android.material.textfield.TextInputEditText
  752.                 android:id="@+id/hotelAddET"
  753.                 android:layout_width="match_parent"
  754.                 android:layout_height="wrap_content"
  755.                 android:padding="15dp"
  756.                 android:textSize="18sp"
  757.                 android:inputType="text" />
  758.  
  759.         </com.google.android.material.textfield.TextInputLayout>
  760.  
  761.  
  762.         <com.google.android.material.textfield.TextInputLayout
  763.             android:layout_width="match_parent"
  764.             android:layout_height="wrap_content"
  765.             android:layout_marginVertical="5dp"
  766.             android:hint="Latitude">
  767.  
  768.             <com.google.android.material.textfield.TextInputEditText
  769.                 android:id="@+id/latitudeET"
  770.                 android:layout_width="match_parent"
  771.                 android:layout_height="wrap_content"
  772.                 android:padding="15dp"
  773.                 android:textSize="18sp"
  774.                 android:inputType="numberDecimal" />
  775.         </com.google.android.material.textfield.TextInputLayout>
  776.  
  777.         <com.google.android.material.textfield.TextInputLayout
  778.             android:layout_width="match_parent"
  779.             android:layout_height="wrap_content"
  780.             android:layout_marginVertical="5dp"
  781.             android:hint="Longitude">
  782.  
  783.             <com.google.android.material.textfield.TextInputEditText
  784.                 android:id="@+id/longitudeET"
  785.                 android:layout_width="match_parent"
  786.                 android:layout_height="wrap_content"
  787.                 android:padding="15dp"
  788.                 android:textSize="18sp"
  789.                 android:inputType="numberDecimal" />
  790.         </com.google.android.material.textfield.TextInputLayout>
  791.  
  792.  
  793.  
  794.  
  795.  
  796.  
  797.  
  798.  
  799.         <com.google.android.material.textfield.TextInputLayout
  800.             android:layout_width="match_parent"
  801.             android:layout_height="wrap_content"
  802.             android:hint="Description"
  803.             android:layout_marginVertical="5dp"
  804.             app:counterMaxLength="400">
  805.  
  806.             <com.google.android.material.textfield.TextInputEditText
  807.                 android:id="@+id/hotelDescET"
  808.                 android:layout_width="match_parent"
  809.                 android:layout_height="wrap_content"
  810.                 android:padding="20dp"
  811.                 android:textSize="18sp"
  812.                 android:inputType="textMultiLine" />
  813.  
  814.         </com.google.android.material.textfield.TextInputLayout>
  815.  
  816.         <com.google.android.material.textfield.TextInputLayout
  817.             android:layout_width="match_parent"
  818.             android:layout_height="wrap_content"
  819.             android:textSize="18sp"
  820.             android:layout_marginVertical="5dp"
  821.             android:hint="Contact Number">
  822.  
  823.             <com.google.android.material.textfield.TextInputEditText
  824.                 android:id="@+id/hotelContactET"
  825.                 android:layout_width="match_parent"
  826.                 android:layout_height="wrap_content"
  827.                 android:padding="15dp"
  828.                 android:textSize="18sp"
  829.                 android:inputType="phone" />
  830.  
  831.         </com.google.android.material.textfield.TextInputLayout>
  832.  
  833.         <com.google.android.material.textfield.TextInputLayout
  834.             android:layout_width="match_parent"
  835.             android:layout_height="wrap_content"
  836.             android:layout_marginVertical="5dp"
  837.             android:hint="Email Address">
  838.  
  839.             <com.google.android.material.textfield.TextInputEditText
  840.                 android:id="@+id/hotelEmailET"
  841.                 android:layout_width="match_parent"
  842.                 android:layout_height="wrap_content"
  843.                 android:textSize="18sp"
  844.                 android:padding="15dp"
  845.                 android:inputType="textEmailAddress" />
  846.  
  847.         </com.google.android.material.textfield.TextInputLayout>
  848.  
  849.         <LinearLayout
  850.             android:id="@+id/roomTypesLayout"
  851.             android:layout_width="match_parent"
  852.             android:layout_height="wrap_content"
  853.             android:orientation="vertical">
  854.  
  855.             <androidx.recyclerview.widget.RecyclerView
  856.                 android:id="@+id/roomTypesRecyclerView"
  857.                 android:layout_width="match_parent"
  858.                 android:layout_height="wrap_content"
  859.                 android:layout_marginTop="16dp" />
  860.  
  861.             <LinearLayout
  862.                 android:id="@+id/roomTypeEntryLayout"
  863.                 android:layout_width="match_parent"
  864.                 android:layout_height="wrap_content"
  865.                 android:orientation="horizontal">
  866.  
  867.                 <com.google.android.material.textfield.TextInputLayout
  868.                     android:layout_width="0dp"
  869.                     android:layout_height="wrap_content"
  870.                     android:layout_weight="1"
  871.                     android:hint="Room Type">
  872.  
  873.                     <com.google.android.material.textfield.TextInputEditText
  874.                         android:id="@+id/roomtypeET"
  875.                         android:layout_width="match_parent"
  876.                         android:layout_height="wrap_content"
  877.                         android:padding="20dp"
  878.                         android:inputType="text" />
  879.  
  880.                 </com.google.android.material.textfield.TextInputLayout>
  881.  
  882.  
  883.             </LinearLayout>
  884.             <TextView
  885.                 android:layout_width="wrap_content"
  886.                 android:layout_height="wrap_content"
  887.                 android:text="Please provide the pricing for each room type"/>
  888.  
  889.  
  890.             <androidx.appcompat.widget.AppCompatButton
  891.                 android:layout_width="wrap_content"
  892.                 android:layout_height="50dp"
  893.                 android:text="Add Room Type"
  894.                 android:id="@+id/addRoomTypeBtn"
  895.                 android:textSize="15sp"
  896.                 android:padding="7dp"
  897.                 android:textColor="@color/textcolor"
  898.                 android:layout_marginTop="8dp"
  899.                 android:layout_marginRight="10dp"
  900.                 android:layout_marginLeft="10dp"
  901.                 android:layout_gravity="center"
  902.                 android:background="@drawable/gradient3" />
  903.  
  904.         </LinearLayout>
  905.  
  906.         <com.google.android.material.textfield.TextInputLayout
  907.             android:layout_width="match_parent"
  908.             android:layout_height="wrap_content"
  909.             android:hint="Add Amenity">
  910.  
  911.             <com.google.android.material.textfield.TextInputEditText
  912.                 android:id="@+id/amenityET"
  913.                 android:layout_width="match_parent"
  914.                 android:layout_height="wrap_content"
  915.                 android:padding="15dp"
  916.                 android:inputType="text" />
  917.  
  918.         </com.google.android.material.textfield.TextInputLayout>
  919.  
  920.         <com.google.android.material.textfield.TextInputLayout
  921.             android:layout_width="match_parent"
  922.             android:layout_height="wrap_content"
  923.             android:hint="Cancellation Policy"
  924.             app:counterEnabled="true">
  925.  
  926.             <com.google.android.material.textfield.TextInputEditText
  927.                 android:id="@+id/cancellationPolicyET"
  928.                 android:layout_width="match_parent"
  929.                 android:layout_height="wrap_content"
  930.                 android:textSize="18sp"
  931.                 android:padding="15dp"
  932.                 android:inputType="textMultiLine" />
  933.  
  934.         </com.google.android.material.textfield.TextInputLayout>
  935.  
  936.         <com.google.android.material.textfield.TextInputLayout
  937.             android:layout_width="match_parent"
  938.             android:layout_height="wrap_content"
  939.             android:hint="Gcash Number"
  940.             app:counterEnabled="true">
  941.  
  942.             <com.google.android.material.textfield.TextInputEditText
  943.                 android:id="@+id/gcashNumber"
  944.                 android:layout_width="match_parent"
  945.                 android:layout_height="wrap_content"
  946.                 android:textSize="18sp"
  947.                 android:padding="15dp"
  948.                 android:inputType="textMultiLine" />
  949.  
  950.         </com.google.android.material.textfield.TextInputLayout>
  951.  
  952.         <com.google.android.material.textfield.TextInputLayout
  953.             android:layout_width="match_parent"
  954.             android:layout_height="wrap_content"
  955.             android:hint="Gcash Name"
  956.             app:counterEnabled="true">
  957.  
  958.             <com.google.android.material.textfield.TextInputEditText
  959.                 android:id="@+id/gcashName"
  960.                 android:layout_width="match_parent"
  961.                 android:layout_height="wrap_content"
  962.                 android:textSize="18sp"
  963.                 android:padding="15dp"
  964.                 android:inputType="textMultiLine" />
  965.  
  966.         </com.google.android.material.textfield.TextInputLayout>
  967.  
  968.         <LinearLayout
  969.             android:layout_width="match_parent"
  970.             android:layout_height="wrap_content"
  971.             android:orientation="horizontal">
  972.  
  973.             <androidx.appcompat.widget.AppCompatButton
  974.                 android:layout_width="0dp"
  975.                 android:layout_weight="1"
  976.                 android:layout_height="50dp"
  977.                 android:layout_gravity="start"
  978.                 android:gravity="center"
  979.                 android:text="Save Changes"
  980.                 android:id="@+id/postButton"
  981.                 android:textSize="15sp"
  982.                 android:padding="7dp"
  983.                 android:textColor="@color/white"
  984.                 android:layout_marginTop="8dp"
  985.                 android:layout_marginRight="10dp"
  986.                 android:layout_marginLeft="10dp"
  987.                 android:background="@drawable/gradient4" />
  988.  
  989.             <androidx.appcompat.widget.AppCompatButton
  990.                 android:layout_width="0dp"
  991.                 android:layout_weight="1"
  992.                 android:layout_height="50dp"
  993.                 android:layout_gravity="start"
  994.                 android:gravity="center"
  995.                 android:text="Cancel"
  996.                 android:id="@+id/cancelButton"
  997.                 android:textSize="15sp"
  998.                 android:padding="7dp"
  999.                 android:textColor="@color/white"
  1000.                 android:layout_marginTop="8dp"
  1001.                 android:layout_marginRight="10dp"
  1002.                 android:layout_marginLeft="10dp"
  1003.                 android:background="@drawable/gradient4" />
  1004.         </LinearLayout>
  1005.  
  1006.     </LinearLayout>
  1007. </ScrollView>
  1008.  
  1009.  
Tags: Code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement