Advertisement
kitlolz012

edithotelactivity java code

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