Advertisement
kitlolz012

konti error

Nov 10th, 2023
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 30.77 KB | Source Code | 0 0
  1. package com.example.gypsy;
  2.  
  3. import static android.content.ContentValues.TAG;
  4.  
  5. import android.app.Activity;
  6. import android.content.Intent;
  7. import android.net.Uri;
  8. import android.os.Bundle;
  9. import android.provider.MediaStore;
  10. import android.util.Log;
  11. import android.widget.Button;
  12. import android.widget.EditText;
  13. import android.widget.ImageView;
  14. import android.widget.LinearLayout;
  15.  
  16.  
  17. import androidx.activity.result.ActivityResultLauncher;
  18. import androidx.activity.result.contract.ActivityResultContracts;
  19. import androidx.annotation.NonNull;
  20. import androidx.appcompat.app.AppCompatActivity;
  21. import androidx.core.content.ContextCompat;
  22. import androidx.recyclerview.widget.LinearLayoutManager;
  23. import androidx.recyclerview.widget.RecyclerView;
  24. import androidx.viewpager2.widget.ViewPager2;
  25.  
  26. import java.io.FileNotFoundException;
  27. import java.io.InputStream;
  28.  
  29. import com.google.android.gms.tasks.OnCompleteListener;
  30. import com.google.android.gms.tasks.OnFailureListener;
  31. import com.google.android.gms.tasks.Task;
  32. import com.google.android.material.floatingactionbutton.FloatingActionButton;
  33. import com.google.android.material.textfield.TextInputEditText;
  34. import com.google.firebase.auth.FirebaseAuth;
  35. import com.google.firebase.auth.FirebaseUser;
  36. import com.google.firebase.database.DataSnapshot;
  37. import com.google.firebase.database.DatabaseError;
  38. import com.google.firebase.database.DatabaseReference;
  39. import com.google.firebase.database.FirebaseDatabase;
  40. import com.google.firebase.database.Query;
  41. import com.google.firebase.database.ValueEventListener;
  42. import com.google.firebase.storage.FirebaseStorage;
  43. import com.google.firebase.storage.StorageReference;
  44. import com.google.firebase.storage.UploadTask;
  45. import java.util.ArrayList;
  46. import java.util.HashMap;
  47. import java.util.List;
  48. import java.util.Map;
  49. import java.util.concurrent.atomic.AtomicInteger;
  50.  
  51. public class EditHotelActivity extends AppCompatActivity {
  52.  
  53.     private List<Uri> imageUris = new ArrayList<>();
  54.     private ActivityResultLauncher<Intent> galleryLauncher;
  55.     private FloatingActionButton uploadButton;
  56.     private TextInputEditText hotelNameET;
  57.     private TextInputEditText hotelAddET;
  58.     private TextInputEditText hotelDescET;
  59.     private TextInputEditText hotelContactET;
  60.     private TextInputEditText hotelEmailET;
  61.     private TextInputEditText roomTypeET;
  62.     private List<String> roomTypes = new ArrayList<>();
  63.     private RoomTypeAdapter roomTypeAdapter;
  64.     private RecyclerView roomTypeRecyclerView;
  65.     private TextInputEditText cancellationPolicyET;
  66.     private TextInputEditText amenityET;
  67.     private TextInputEditText gcashNumberET;
  68.     private TextInputEditText gcashNameET;
  69.     private Button postButton, cancelButton;
  70.     private Uri imageUri;
  71.     private StorageReference storageReference;
  72.     private DatabaseReference databaseReference;
  73.     private String userId;
  74.     private HotelImageSliderAdapter adapter;
  75.     private ViewPager2 viewPager;
  76.     private LinearLayout dotsLayout;
  77.     private ImageView[] dots;
  78.  
  79.     @Override
  80.     protected void onCreate(Bundle savedInstanceState) {
  81.         super.onCreate(savedInstanceState);
  82.         setContentView(R.layout.activity_edit_hotel);
  83.  
  84.         viewPager = findViewById(R.id.viewPager);
  85.         dotsLayout = findViewById(R.id.dotsLayout);
  86.         uploadButton = findViewById(R.id.uploadButton);
  87.         hotelNameET = findViewById(R.id.hotelNameET);
  88.         hotelAddET = findViewById(R.id.hotelAddET);
  89.         hotelDescET = findViewById(R.id.hotelDescET);
  90.         hotelContactET = findViewById(R.id.hotelContactET);
  91.         hotelEmailET = findViewById(R.id.hotelEmailET);
  92.         roomTypeET = findViewById(R.id.roomtypeET);
  93.         amenityET = findViewById(R.id.amenityET);
  94.         cancellationPolicyET = findViewById(R.id.cancellationPolicyET);
  95.         gcashNumberET = findViewById(R.id.gcashNumber);
  96.         gcashNameET = findViewById(R.id.gcashName);
  97.         postButton = findViewById(R.id.postButton);
  98.  
  99.         roomTypeRecyclerView = findViewById(R.id.roomTypesRecyclerView);
  100.         roomTypeAdapter = new RoomTypeAdapter(roomTypes, new RoomTypeAdapter.OnRoomTypeDeleteListener() {
  101.             @Override
  102.             public void deleteRoomType(String roomType) {
  103.                 getHotelId(new HotelIdCallback() {
  104.                     @Override
  105.                     public void onHotelIdReceived(String hotelId) {
  106.                         if (hotelId != null) {
  107.                             DatabaseReference hotelRef = databaseReference.child("hotels").child(hotelId);
  108.  
  109.                             // Fetch the current room types
  110.                             hotelRef.child("roomTypes").addListenerForSingleValueEvent(new ValueEventListener() {
  111.                                 @Override
  112.                                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  113.                                     if (dataSnapshot.exists()) {
  114.                                         List<String> currentRoomTypes = new ArrayList<>();
  115.  
  116.                                         for (DataSnapshot roomTypeSnapshot : dataSnapshot.getChildren()) {
  117.                                             String existingRoomType = roomTypeSnapshot.getValue(String.class);
  118.                                             if (!roomType.equals(existingRoomType)) {
  119.                                                 currentRoomTypes.add(existingRoomType);
  120.                                             }
  121.                                         }
  122.  
  123.                                         // Update the room types in the Firebase Realtime Database
  124.                                         updateRoomTypesInDatabase(hotelRef, currentRoomTypes);
  125.                                     }
  126.                                 }
  127.  
  128.                                 @Override
  129.                                 public void onCancelled(@NonNull DatabaseError databaseError) {
  130.                                     Log.e("deleteRoomType", "Error: " + databaseError.getMessage());
  131.                                 }
  132.                             });
  133.                         } else {
  134.                             Log.e("deleteRoomType", "Hotel ID is null");
  135.                         }
  136.                     }
  137.                 });
  138.             }
  139.         });
  140.  
  141.  
  142.         roomTypeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
  143.         roomTypeRecyclerView.setAdapter(roomTypeAdapter);
  144.  
  145.         roomTypeET = findViewById(R.id.roomtypeET);
  146.         Button addRoomTypeBtn = findViewById(R.id.addRoomTypeBtn);
  147.  
  148.         // dynamically pag-add ng room types nila
  149.         addRoomTypeBtn.setOnClickListener(v -> {
  150.             String roomType = roomTypeET.getText().toString().trim();
  151.             if (!roomType.isEmpty()) {
  152.                 roomTypes.add(roomType);
  153.                 roomTypeAdapter.notifyDataSetChanged();
  154.                 roomTypeET.setText("");
  155.             }
  156.         });
  157.  
  158.         FirebaseAuth auth = FirebaseAuth.getInstance();
  159.         FirebaseUser currentUser = auth.getCurrentUser();
  160.         userId = currentUser.getUid();
  161.  
  162.         FirebaseStorage storage = FirebaseStorage.getInstance();
  163.         storageReference = storage.getReference();
  164.         FirebaseDatabase database = FirebaseDatabase.getInstance();
  165.         databaseReference = database.getReference();
  166.  
  167.         // adapter para sa multiple images ng hotel, slider
  168.         adapter = new HotelImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  169.         viewPager.setAdapter(adapter);
  170.  
  171.         // yung dots nag-iindicate ng pang ilang images na, parang sa ig
  172.         dotsLayout = findViewById(R.id.dotsLayout);
  173.         HotelImageSliderAdapter adapter = new HotelImageSliderAdapter(this, imageUris, viewPager, dotsLayout);
  174.         viewPager.setAdapter(adapter);
  175.  
  176.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  177.             @Override
  178.             public void onPageSelected(int position) {
  179.                 super.onPageSelected(position);
  180.                 adapter.updateDotsIndicator(position);
  181.             }
  182.         });
  183.  
  184.         adapter.updateDotsIndicator(0);
  185.  
  186.         // gallery
  187.         galleryLauncher = registerForActivityResult(
  188.                 new ActivityResultContracts.StartActivityForResult(),
  189.                 result -> {
  190.                     if (result.getResultCode() == Activity.RESULT_OK) {
  191.                         Intent data = result.getData();
  192.                         if (data != null && data.getData() != null) {
  193.                             imageUri = data.getData();
  194.                             imageUris.add(imageUri);
  195.  
  196.                             adapter.notifyDataSetChanged();
  197.                         }
  198.                     }
  199.                 }
  200.         );
  201.  
  202.         uploadButton.setOnClickListener(v -> openGallery());
  203.  
  204.         // button "save changes" mapopost na sa tourist interface
  205.         postButton.setOnClickListener(v -> {
  206.             String hotelName = hotelNameET.getText().toString();
  207.             String hotelAddress = hotelAddET.getText().toString();
  208.             String hotelDescription = hotelDescET.getText().toString();
  209.             String hotelContact = hotelContactET.getText().toString();
  210.             String hotelEmail = hotelEmailET.getText().toString();
  211.             String roomType = roomTypeET.getText().toString();
  212.             String cancellationPolicy = cancellationPolicyET.getText().toString();
  213.             String amenitiesHotel = amenityET.getText().toString();
  214.             String gcashNumber = gcashNumberET.getText().toString();
  215.             String gcashName = gcashNameET.getText().toString();
  216.  
  217.  
  218.             checkIfExists(userId, hotelName, hotelAddress, hotelDescription, hotelContact, hotelEmail, roomTypes, cancellationPolicy, imageUri, amenitiesHotel, gcashNumber, gcashName);
  219.  
  220.             // back to HotelEditFrag, or yung read-only, na nakaretrieve na
  221.             Intent intent = new Intent(this, MainActivity2.class);
  222.             intent.putExtra("fragmentToLoad", "HotelEditFragment");
  223.             startActivity(intent);
  224.         });
  225.  
  226.  
  227.         retrieve(userId);
  228.  
  229.  
  230.  
  231.         addDotsIndicator(0); // para lang to sa dots sa image slider
  232.         viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
  233.             @Override
  234.             public void onPageSelected(int position) {
  235.                 super.onPageSelected(position);
  236.                 addDotsIndicator(position);
  237.             }
  238.         });
  239.  
  240.         Log.d(TAG, "image upload triggeredd");
  241.     }
  242.  
  243.     // if nag eexist na yung user sa "hotels", di na pwede mag generate ng new set of data, para iwas doble doeble
  244.     private void checkIfExists(String userId, String hotelName, String hotelAddress, String hotelDescription, String hotelContact, String hotelEmail, List<String> roomTypes,
  245.                                String cancellationPolicy, Uri imageUri, String amenitiesHotel, String gcashNumber, String gcashName) {
  246.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  247.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  248.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  249.             @Override
  250.             // pag nag-eexist na, mag uupdate nalang yung existing data instead na gumawa ng new
  251.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  252.                 if (dataSnapshot.exists()) {
  253.                     String existingHotelId = dataSnapshot.getChildren().iterator().next().getKey();
  254.                     update(hotelName, hotelAddress, hotelDescription, imageUris, hotelContact, hotelEmail, roomTypes,
  255.                             cancellationPolicy, existingHotelId, amenitiesHotel, gcashNumber, gcashName);
  256.                     adapter.setUris(imageUris);
  257.                     adapter.notifyDataSetChanged();
  258.                     Log.d(TAG, "hotel exists, id: " + userId);
  259.                 } else {
  260.                     // if hindi pa nag-eeexist, gagawa ng new data under "hotels"
  261.                     create(userId, hotelName, hotelAddress, hotelDescription, hotelContact, hotelEmail, roomTypes,
  262.                             cancellationPolicy, imageUris, amenitiesHotel, gcashNumber, gcashName);
  263.                     adapter.setUris(imageUris);
  264.                     adapter.notifyDataSetChanged();
  265.                     Log.d(TAG, "hotel dont exist: .getText().getText() " + userId);
  266.                 }
  267.             }
  268.  
  269.             @Override
  270.             public void onCancelled(@NonNull DatabaseError databaseError) {
  271.                 Log.e("check", "error" + databaseError.getMessage());
  272.             }
  273.         });
  274.     }
  275.  
  276.     private void create(String userId, String hotelName, String hotelAddress, String hotelDescription,
  277.                         String hotelContact, String hotelEmail, List<String> roomTypes,
  278.                         String cancellationPolicy, List<Uri> imageUris, String amenitiesHotel,
  279.                         String gcashNumber, String gcashName) {
  280.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  281.  
  282.         DatabaseReference hotelRef = hotelsRef.push();
  283.         String hotelId = hotelRef.getKey();
  284.  
  285.         List<String> imageUrls = new ArrayList<>();
  286.         AtomicInteger uploadCount = new AtomicInteger(0);
  287.  
  288.         for (int i = 0; i < imageUris.size(); i++) {
  289.             final int finalIndex = i;
  290.             Uri imageUri = imageUris.get(i);
  291.             try {
  292.  
  293.                 // Convert Uri to InputStream
  294.                 InputStream imageInputStream = getContentResolver().openInputStream(imageUri);
  295.  
  296.  
  297.                 if (imageInputStream != null) {
  298.                     StorageReference imageRef = storageReference.child("hotel_images/" + hotelId + "/image" + (i + 1));
  299.                     UploadTask uploadTask = imageRef.putStream(imageInputStream);
  300.  
  301.                     uploadTask.addOnFailureListener(new MyFailureListener());
  302.                     uploadTask.addOnSuccessListener(taskSnapshot -> {
  303.  
  304.                         imageRef.getDownloadUrl().addOnCompleteListener(task -> {
  305.                             if (task.isSuccessful() && task.getResult() != null) {
  306.                                 String url = task.getResult().toString();
  307.                                 imageUrls.add(url);
  308.  
  309.                                 if (uploadCount.incrementAndGet() == imageUris.size()) {
  310.                                     save(hotelId, imageUrls, hotelName, hotelAddress, hotelDescription,
  311.                                             hotelContact, hotelEmail, roomTypes, cancellationPolicy,
  312.                                             amenitiesHotel, gcashNumber, gcashName);
  313.                                     saveImages(hotelId, imageUrls);
  314.  
  315.                                     adapter.setUris(imageUris);
  316.                                     adapter.notifyDataSetChanged();
  317.                                 }
  318.  
  319.                             }
  320.                         });
  321.                     });
  322.                 } else {
  323.                     Log.e(TAG, "ImageInputStream is null. Handle this case accordingly.");
  324.                 }
  325.             } catch (FileNotFoundException e) {
  326.                 e.printStackTrace();
  327.                 Log.e(TAG, "Unexpected error: " + e.getMessage());
  328.             }
  329.         }
  330.     }
  331.  
  332.     private void update(String hotelName, String hotelAddress, String hotelDescription,
  333.                         List<Uri> imageUris, String hotelContact, String hotelEmail,
  334.                         List<String> roomTypes, String cancellationPolicy, String hotelId,
  335.                         String amenitiesHotel, String gcashNumber, String gcashName) {
  336.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  337.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  338.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  339.             @Override
  340.             public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {
  341.                 if (dataSnapshot.exists()) {
  342.                     for (com.google.firebase.database.DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
  343.                         String hotelId = childSnapshot.getKey();
  344.  
  345.                         DatabaseReference hotelRef = hotelsRef.child(hotelId);
  346.                         hotelRef.child("name").setValue(hotelName);
  347.                         hotelRef.child("address").setValue(hotelAddress);
  348.                         hotelRef.child("description").setValue(hotelDescription);
  349.                         hotelRef.child("contact").setValue(hotelContact);
  350.                         hotelRef.child("email").setValue(hotelEmail);
  351.                         hotelRef.child("cancellationPolicy").setValue(cancellationPolicy);
  352.                         hotelRef.child("amenities").setValue(amenitiesHotel);
  353.                         hotelRef.child("gcashNumber").setValue(gcashNumber);
  354.                         hotelRef.child("gcashName").setValue(gcashName);
  355.                         saveRoomTypes(hotelId, roomTypes);
  356.  
  357.                         if (!imageUris.isEmpty()) {
  358.                             List<String> imageUrls = new ArrayList<>();
  359.  
  360.                             for (int i = 0; i < imageUris.size(); i++) {
  361.                                 if (imageUris.get(i) != null) {
  362.                                     Uri imageUri = imageUris.get(i);
  363.  
  364.                                     try {
  365.                                         // Convert Uri to InputStream
  366.  
  367.                                         InputStream imageInputStream = getContentResolver().openInputStream(imageUri);
  368.  
  369.                                         if (imageInputStream != null) {
  370.                                             StorageReference imageRef = storageReference.child("hotel_images/" + hotelId + "/image" + (i + 1));
  371.                                             UploadTask uploadTask = imageRef.putStream(imageInputStream);
  372.  
  373.                                             // Rest of your code for uploading the image
  374.                                             uploadTask.addOnFailureListener(new OnFailureListener() {
  375.                                                 @Override
  376.                                                 public void onFailure(@NonNull Exception e) {
  377.                                                     Log.e("image upload", "Error during upload: " + e.getMessage());
  378.                                                 }
  379.                                             });
  380.  
  381.                                             uploadTask.addOnFailureListener(new MyFailureListener());
  382.                                             uploadTask.addOnSuccessListener(taskSnapshot -> imageRef.getDownloadUrl().addOnSuccessListener(downloadUri -> {
  383.                                                 String imageUrl = downloadUri.toString();
  384.                                                 imageUrls.add(imageUrl);
  385.  
  386.                                                 if (imageUrls.size() == imageUris.size()) {
  387.                                                     saveImages(hotelId, imageUrls);
  388.                                                 }
  389.                                                 Log.d(TAG, "Image URL: " + imageUrl);
  390.                                             })).addOnFailureListener(e -> {
  391.                                                 Log.e("image upload", "error");
  392.                                                 Log.e("image upload", "Firebase Storage Error: " + e.getMessage());
  393.                                             });
  394.                                         } else {
  395.                                             Log.e(TAG, "ImageInputStream is null. Handle this case accordingly.");
  396.                                         }
  397.                                     } catch (FileNotFoundException e) {
  398.                                         e.printStackTrace();
  399.                                         Log.e(TAG, "FileNotFoundException: " + e.getMessage());
  400.                                     }
  401.  
  402.                                 }
  403.                             }
  404.                         }
  405.                     }
  406.                 }
  407.             }
  408.  
  409.             @Override
  410.             public void onCancelled(@NonNull DatabaseError databaseError) {
  411.                 Log.e("update", "error" + databaseError.getMessage());
  412.             }
  413.         });
  414.     }
  415.  
  416.     private void openGallery() {
  417.         // lalagyan natin to ng permission first
  418.         Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  419.         galleryLauncher.launch(galleryIntent);
  420.     }
  421.  
  422.     // always save changes
  423.     private void save(String hotelId, List<String> imageUrls, String hotelName, String hotelAddress, String hotelDescription,
  424.                       String hotelContact, String hotelEmail, List<String> roomTypes, String cancellationPolicy, String amenitiesHotel,
  425.                       String gcashNumber, String gcashName) {
  426.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  427.         DatabaseReference hotelRef = hotelsRef.child(hotelId);
  428.  
  429.         // set sa rdb yung value
  430.         hotelRef.child("name").setValue(hotelName);
  431.         hotelRef.child("address").setValue(hotelAddress);
  432.         hotelRef.child("description").setValue(hotelDescription);
  433.         hotelRef.child("contact").setValue(hotelContact);
  434.         hotelRef.child("email").setValue(hotelEmail);
  435.         hotelRef.child("cancellationPolicy").setValue(cancellationPolicy);
  436.         hotelRef.child("user_id").setValue(userId);
  437.         hotelRef.child("amenities").setValue(amenitiesHotel);
  438.         hotelRef.child("gcashNumber").setValue(gcashNumber);
  439.         hotelRef.child("gcashName").setValue(gcashName);
  440.  
  441.         Map<String, Object> imagesMap = new HashMap<>();
  442.         for (int i = 0; i < imageUrls.size(); i++) {
  443.             imagesMap.put("image" + (i + 1), imageUrls.get(i));
  444.         }
  445.         hotelRef.child("images").setValue(imagesMap);
  446.  
  447.         Map<String, Object> roomTypesMap = new HashMap<>();
  448.         for (int i = 0; i < roomTypes.size(); i++) {
  449.             roomTypesMap.put("roomType" + (i + 1), roomTypes.get(i));
  450.         }
  451.         hotelRef.child("roomTypes").setValue(roomTypesMap);
  452.     }
  453.  
  454.     // then reretrieve natin sa mga edit texts
  455.     private void retrieve(String userId) {
  456.         DatabaseReference hotelsRef = databaseReference.child("hotels");
  457.         Query query = hotelsRef.orderByChild("user_id").equalTo(userId);
  458.         query.addListenerForSingleValueEvent(new ValueEventListener() {
  459.             @Override
  460.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  461.  
  462.  
  463.  
  464.                 if (dataSnapshot.exists()) {
  465.                     DataSnapshot hotelSnapshot = dataSnapshot.getChildren().iterator().next();
  466.  
  467.                     String title = hotelSnapshot.child("name").getValue(String.class);
  468.                     String hotelAddress = hotelSnapshot.child("address").getValue(String.class);
  469.                     String description = hotelSnapshot.child("description").getValue(String.class);
  470.                     String hotelContact = hotelSnapshot.child("contact").getValue(String.class);
  471.                     String hotelEmail = hotelSnapshot.child("email").getValue(String.class);
  472.                     String cancellationPolicy = hotelSnapshot.child("cancellationPolicy").getValue(String.class);
  473.                     String amenitiesHotel = hotelSnapshot.child("amenities").getValue(String.class);
  474.                     String gcashNumber = hotelSnapshot.child("gcashNumber").getValue(String.class);
  475.                     String gcashName = hotelSnapshot.child("gcashName").getValue(String.class);
  476.  
  477.                     DataSnapshot roomTypesSnapshot = hotelSnapshot.child("roomTypes");
  478.                     List<String> roomTypes = new ArrayList<>();
  479.                     for (DataSnapshot roomTypeSnapshot : roomTypesSnapshot.getChildren()) {
  480.                         String roomType = roomTypeSnapshot.getValue(String.class);
  481.                         roomTypes.add(roomType);
  482.                     }
  483.  
  484.                     List<String> imageUrls = new ArrayList<>();
  485.                     DataSnapshot imagesSnapshot = hotelSnapshot.child("images");
  486.                     for (DataSnapshot imageSnapshot : imagesSnapshot.getChildren()) {
  487.                         imageUrls.clear();
  488.                         String imageUrl = imageSnapshot.getValue(String.class);
  489.                         Log.d(TAG, "Image URL: " + imageUrl);
  490.                         imageUrls.add(imageUrl);
  491.  
  492.  
  493.                     }
  494.  
  495.                     hotelNameET.setText(title);
  496.                     hotelDescET.setText(description);
  497.                     hotelAddET.setText(hotelAddress);
  498.                     hotelContactET.setText(hotelContact);
  499.                     hotelEmailET.setText(hotelEmail);
  500.                     cancellationPolicyET.setText(cancellationPolicy);
  501.                     amenityET.setText(amenitiesHotel);
  502.                     gcashNumberET.setText(gcashNumber);
  503.                     gcashNameET.setText(gcashName);
  504.                     imageUris.clear();
  505.  
  506.                     imageUris.clear();
  507.                     for (String imageUrl : imageUrls) {
  508.                         imageUris.add(Uri.parse(imageUrl));
  509.                     }
  510.  
  511.                     adapter.setUris(imageUris);
  512.                     adapter.notifyDataSetChanged();
  513.  
  514.                     roomTypeAdapter.setRoomTypes(roomTypes);
  515.                     roomTypeAdapter.notifyDataSetChanged();
  516.                 }
  517.             }
  518.  
  519.             @Override
  520.             public void onCancelled(@NonNull DatabaseError databaseError) {
  521.                 Log.e("retrieve", "error" + databaseError.getMessage());
  522.             }
  523.         });
  524.     }
  525.  
  526.     private void addDotsIndicator(int position) { // again for dots lang nung image slider
  527.         dots = new ImageView[imageUris.size()];
  528.         dotsLayout.removeAllViews();
  529.  
  530.         for (int i = 0; i < dots.length; i++) {
  531.             dots[i] = new ImageView(this);
  532.             dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_unselected));
  533.  
  534.             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
  535.                     LinearLayout.LayoutParams.WRAP_CONTENT,
  536.                     LinearLayout.LayoutParams.WRAP_CONTENT
  537.             );
  538.  
  539.             params.setMargins(8, 0, 8, 0);
  540.             dotsLayout.addView(dots[i], params);
  541.         }
  542.         if (dots.length > 0) {
  543.             dots[position].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.dots_selected));
  544.         }
  545.     }
  546.  
  547.     private void saveImages(String hotelId, List<String> imageUrls) {
  548.         DatabaseReference imagesRef = databaseReference.child("hotels").child(hotelId).child("images");
  549.  
  550.         for (int i = 0; i < imageUrls.size(); i++) {
  551.             imagesRef.child("image" + (i + 1)).setValue(imageUrls.get(i));
  552.         }
  553.     }
  554.  
  555.     private void saveRoomTypes(String hotelId, List<String> roomTypes) {
  556.         DatabaseReference roomTypesRef = databaseReference.child("hotels").child(hotelId).child("roomTypes");
  557.  
  558.         if (roomTypes != null) {
  559.             for (int i = 0; i < roomTypes.size(); i++) {
  560.                 String roomType = roomTypes.get(i);
  561.                 if (roomType != null) {
  562.                     roomTypesRef.child("roomType" + (i + 1)).setValue(roomType);
  563.                 }
  564.             }
  565.         }
  566.     }
  567.  
  568.     private void deleteRoomType(String roomType) {
  569.         getHotelId(new HotelIdCallback() {
  570.             @Override
  571.             public void onHotelIdReceived(String hotelId) {
  572.                 if (hotelId != null) {
  573.                     DatabaseReference hotelRef = databaseReference.child("hotels").child(hotelId);
  574.  
  575.                     // Fetch the current room types
  576.                     hotelRef.child("roomTypes").addListenerForSingleValueEvent(new ValueEventListener() {
  577.                         @Override
  578.                         public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  579.                             if (dataSnapshot.exists()) {
  580.                                 List<String> currentRoomTypes = new ArrayList<>();
  581.  
  582.                                 for (DataSnapshot roomTypeSnapshot : dataSnapshot.getChildren()) {
  583.                                     String existingRoomType = roomTypeSnapshot.getValue(String.class);
  584.                                     if (!roomType.equals(existingRoomType)) {
  585.                                         currentRoomTypes.add(existingRoomType);
  586.                                     }
  587.                                 }
  588.  
  589.                                 // Update the room types in the Firebase Realtime Database
  590.                                 updateRoomTypesInDatabase(hotelRef, currentRoomTypes);
  591.                             }
  592.                         }
  593.  
  594.                         @Override
  595.                         public void onCancelled(@NonNull DatabaseError databaseError) {
  596.                             Log.e("deleteRoomType", "Error: " + databaseError.getMessage());
  597.                         }
  598.                     });
  599.                 } else {
  600.                     Log.e("deleteRoomType", "Hotel ID is null");
  601.                 }
  602.             }
  603.         });
  604.     }
  605.  
  606.     private void updateRoomTypesInDatabase(DatabaseReference hotelRef, List<String> roomTypes) {
  607.         // Set the updated room types in the database
  608.         hotelRef.child("roomTypes").removeValue(); // Remove the old room types
  609.  
  610.         Map<String, Object> roomTypesMap = new HashMap<>();
  611.         for (int i = 0; i < roomTypes.size(); i++) {
  612.             roomTypesMap.put("roomType" + (i + 1), roomTypes.get(i));
  613.         }
  614.         hotelRef.child("roomTypes").updateChildren(roomTypesMap);
  615.     }
  616.  
  617.     private void getHotelId(HotelIdCallback callback) {
  618.         FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
  619.         if (currentUser != null) {
  620.             String currentUserId = currentUser.getUid();
  621.  
  622.             DatabaseReference hotelRef = FirebaseDatabase.getInstance().getReference("hotels");
  623.             Query query = hotelRef.orderByChild("user_id").equalTo(currentUserId);
  624.  
  625.             query.addListenerForSingleValueEvent(new ValueEventListener() {
  626.                 @Override
  627.                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  628.                     if (dataSnapshot.exists()) {
  629.                         String hotelId = dataSnapshot.getChildren().iterator().next().getKey();
  630.                         callback.onHotelIdReceived(hotelId);
  631.                     } else {
  632.                         callback.onHotelIdReceived(null);
  633.                     }
  634.                 }
  635.  
  636.                 @Override
  637.                 public void onCancelled(@NonNull DatabaseError databaseError) {
  638.                     // Handle errors or failures
  639.                 }
  640.             });
  641.         } else {
  642.             callback.onHotelIdReceived(null);
  643.         }
  644.     }
  645.  
  646.     private interface HotelIdCallback {
  647.         void onHotelIdReceived(String hotelId);
  648.     }
  649.  
  650.  
  651. }
Tags: Android
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement