Advertisement
kitlolz012

BookFormJava(No Multiple Booking)

Oct 6th, 2023
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.96 KB | Source Code | 0 0
  1. package com.example.gypsy;
  2.  
  3. import androidx.annotation.NonNull;
  4. import androidx.appcompat.app.AppCompatActivity;
  5.  
  6. import android.app.DatePickerDialog;
  7. import android.content.Intent;
  8. import android.net.Uri;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.widget.ArrayAdapter;
  13. import android.widget.Button;
  14. import android.widget.DatePicker;
  15. import android.widget.EditText;
  16. import android.widget.ImageView;
  17. import android.widget.NumberPicker;
  18. import android.widget.Spinner;
  19. import android.widget.Toast;
  20.  
  21. import com.google.firebase.auth.FirebaseAuth;
  22. import com.google.firebase.auth.FirebaseUser;
  23. import com.google.firebase.database.DataSnapshot;
  24. import com.google.firebase.database.DatabaseError;
  25. import com.google.firebase.database.DatabaseReference;
  26. import com.google.firebase.database.FirebaseDatabase;
  27. import com.google.firebase.database.ValueEventListener;
  28. import com.google.firebase.storage.FirebaseStorage;
  29. import com.google.firebase.storage.StorageReference;
  30. import com.google.firebase.storage.UploadTask;
  31. import com.google.android.gms.tasks.OnFailureListener;
  32. import com.google.android.gms.tasks.OnSuccessListener;
  33.  
  34. import java.text.ParseException;
  35. import java.text.SimpleDateFormat;
  36. import java.util.ArrayList;
  37. import java.util.Calendar;
  38. import java.util.Date;
  39. import java.util.List;
  40. import java.util.Locale;
  41.  
  42. public class BookForm extends AppCompatActivity {
  43.     private Spinner roomPreferenceSpinner;
  44.     private List<String> roomTypeList = new ArrayList<>();
  45.     private EditText fullNameET;
  46.     private EditText contactNumberET;
  47.     private EditText emailET;
  48.     private EditText checkInDateET;
  49.     private EditText checkOutDateET;
  50.     private NumberPicker adultsNumberPicker;
  51.     private NumberPicker childrenNumberPicker;
  52.     private EditText yourGcashNameET;
  53.     private EditText yourGcashNumberET;
  54.     private EditText referenceNumberET;
  55.     private Button submitButton;
  56.     private ImageView attachedImageView;
  57.     private static final int PICK_IMAGE_REQUEST = 1;
  58.     private Uri selectedImageUri; // To store the selected image URI
  59.  
  60.     // Add these variables as class members
  61.     private Calendar currentDate = Calendar.getInstance();
  62.     private Calendar checkInDateCalendar = Calendar.getInstance();
  63.     private Calendar checkOutDateCalendar = Calendar.getInstance();
  64.  
  65.     @Override
  66.     protected void onCreate(Bundle savedInstanceState) {
  67.         super.onCreate(savedInstanceState);
  68.         setContentView(R.layout.activity_book_form);
  69.  
  70.         Intent intent = getIntent(); // kunin yung hotelId sa DynamicHotel para sa
  71.         String hotelId = intent.getStringExtra("hotelKey"); // personalized fields nila
  72.         Log.d("BookFormActivity", "hotelId: " + hotelId); // sa book info like roomtypes etc
  73.  
  74.         DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
  75.         DatabaseReference roomPreferencesRef = databaseReference.child("hotels").child(hotelId).child("roomTypes");
  76.  
  77.         fullNameET = findViewById(R.id.fullNameET);
  78.         contactNumberET = findViewById(R.id.contactNumberET);
  79.         emailET = findViewById(R.id.emailET);
  80.         submitButton = findViewById(R.id.submitButton);
  81.         roomPreferenceSpinner = findViewById(R.id.roomPreferenceSpinner);
  82.         checkInDateET = findViewById(R.id.checkInDateET);
  83.         checkOutDateET = findViewById(R.id.checkOutDateET);
  84.         yourGcashNameET = findViewById(R.id.yourGcashNameET);
  85.         yourGcashNumberET = findViewById(R.id.yourGcashNumberET);
  86.         referenceNumberET = findViewById(R.id.referenceNumberET);
  87.         attachedImageView = findViewById(R.id.attachedImageView);
  88.  
  89.         ArrayAdapter<String> roomTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, roomTypeList); // list string ng mga items
  90.         roomTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  // built in layout ni AS para sa dropdown selection
  91.  
  92.         roomPreferenceSpinner.setAdapter(roomTypeAdapter);
  93.  
  94.         adultsNumberPicker = findViewById(R.id.adultsNumberPicker);
  95.         childrenNumberPicker = findViewById(R.id.childrenNumberPicker);
  96.         adultsNumberPicker.setMinValue(0);
  97.         adultsNumberPicker.setMaxValue(10);
  98.         childrenNumberPicker.setMinValue(0);
  99.         childrenNumberPicker.setMaxValue(10);
  100.  
  101.         checkInDateET.setOnClickListener(new View.OnClickListener() {
  102.             @Override
  103.             public void onClick(View v) {
  104.                 showDatePickerDialog(checkInDateET);
  105.             }
  106.         });
  107.         checkOutDateET.setOnClickListener(new View.OnClickListener() {
  108.             @Override
  109.             public void onClick(View v) {
  110.                 showDatePickerDialog(checkOutDateET);
  111.             }
  112.         });
  113.  
  114.         roomPreferencesRef.addListenerForSingleValueEvent(new ValueEventListener() {
  115.             @Override
  116.             public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  117.                 if (dataSnapshot.exists()) { // then loop para mag iterate sa children ng DataSnapshot
  118.                     for (DataSnapshot preferenceSnapshot : dataSnapshot.getChildren()) {
  119.                         String roomPreference = preferenceSnapshot.getValue(String.class);
  120.                         roomTypeList.add(roomPreference);
  121.                     }
  122.                     roomTypeAdapter.notifyDataSetChanged();
  123.                 }
  124.             }
  125.  
  126.             @Override
  127.             public void onCancelled(@NonNull DatabaseError databaseError) {
  128.                 Log.e("BookForm", "error" + databaseError.getMessage());
  129.             }
  130.         });
  131.  
  132.         // Parse the check-in and check-out dates to Calendar objects
  133.         checkInDateCalendar = parseDate(checkInDateET.getText().toString());
  134.         checkOutDateCalendar = parseDate(checkOutDateET.getText().toString());
  135.  
  136.         // Check if the current date is within the check-in and check-out date range
  137.         if (isCurrentDateInRange(currentDate, checkInDateCalendar, checkOutDateCalendar)) {
  138.             // If it's within the range, disable the submit button
  139.             submitButton.setEnabled(false);
  140.         }
  141.  
  142.         submitButton.setOnClickListener(new View.OnClickListener() {
  143.             @Override
  144.             public void onClick(View v) {
  145.                 if (allFields()) {
  146.                     FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
  147.  
  148.                     if (currentUser != null) {
  149.                         String userId = currentUser.getUid();
  150.                         String fullName = fullNameET.getText().toString();
  151.                         String checkInDate = checkInDateET.getText().toString();
  152.                         String checkOutDate = checkOutDateET.getText().toString();
  153.                         int adults = adultsNumberPicker.getValue();
  154.                         int children = childrenNumberPicker.getValue();
  155.                         String contactNumber = contactNumberET.getText().toString();
  156.                         String email = emailET.getText().toString();
  157.                         String roomPreference = roomPreferenceSpinner.getSelectedItem().toString();
  158.                         String yourGcashName = yourGcashNameET.getText().toString();
  159.                         String yourGcashNumber = yourGcashNumberET.getText().toString();
  160.                         String referenceNumber = referenceNumberET.getText().toString();
  161.  
  162.                         // Save the booking data, including the image
  163.                         save(userId, hotelId, fullName, checkInDate, checkOutDate,
  164.                                 adults, children, contactNumber, email, roomPreference,
  165.                                 yourGcashName, yourGcashNumber, referenceNumber);
  166.  
  167.                         Toast.makeText(BookForm.this, "Booking submitted.", Toast.LENGTH_SHORT).show();
  168.                     } else {
  169.                         Log.e("BookForm", "User is not authenticated");
  170.                     }
  171.                 } else {
  172.                     Toast.makeText(BookForm.this, "Please fill in all required fields.", Toast.LENGTH_SHORT).show();
  173.                 }
  174.             }
  175.         });
  176.  
  177.         // Attach an OnClickListener to the "Attach Photo" button
  178.         Button attachPhotoButton = findViewById(R.id.attachPhotoButton);
  179.         attachPhotoButton.setOnClickListener(new View.OnClickListener() {
  180.             @Override
  181.             public void onClick(View v) {
  182.                 openFileChooser();
  183.             }
  184.         });
  185.     }
  186.  
  187.     // Open the file chooser to select an image
  188.     private void openFileChooser() {
  189.         Intent intent = new Intent();
  190.         intent.setType("image/*");
  191.         intent.setAction(Intent.ACTION_GET_CONTENT);
  192.         startActivityForResult(intent, PICK_IMAGE_REQUEST);
  193.     }
  194.  
  195.     // Handle the selected image
  196.     @Override
  197.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  198.         super.onActivityResult(requestCode, resultCode, data);
  199.  
  200.         if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
  201.             selectedImageUri = data.getData();
  202.             attachedImageView.setImageURI(selectedImageUri);
  203.             attachedImageView.setVisibility(View.VISIBLE);
  204.         }
  205.     }
  206.  
  207.     // Save booking data and the attached image to Firebase
  208.     private void save(String userId, String hotelId, String fullName, String checkInDate, String checkOutDate,
  209.                       int adults, int children, String contactNumber, String email, String roomPreference,
  210.                       String yourGcashName, String yourGcashNumber, String referenceNumber) {
  211.         FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
  212.  
  213.         if (currentUser != null) {
  214.             String userType = "Tourist"; // select yung user type which is tourist
  215.             //  kukunin yung name for Tourist user type
  216.             String userPath = "users/" + userType + "/" + currentUser.getUid() + "/name";
  217.  
  218.             DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
  219.             DatabaseReference userRef = databaseReference.child(userPath);
  220.             userRef.addListenerForSingleValueEvent(new ValueEventListener() {
  221.                 @Override
  222.                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  223.                     if (dataSnapshot.exists()) {
  224.                         String userName = dataSnapshot.getValue(String.class);
  225.  
  226.                         DatabaseReference hotelRef = databaseReference.child("hotels").child(hotelId).child("user_id");
  227.                         hotelRef.addListenerForSingleValueEvent(new ValueEventListener() {
  228.                             @Override
  229.                             public void onDataChange(@NonNull DataSnapshot hotelDataSnapshot) {
  230.                                 if (hotelDataSnapshot.exists()) {
  231.                                     String hotelUserId = hotelDataSnapshot.getValue(String.class);
  232.  
  233.                                     // Store the image in Firebase Storage (replace "dummy_path" with your actual storage path)
  234.                                     if (selectedImageUri != null) {
  235.                                         StorageReference storageReference = FirebaseStorage.getInstance().getReference();
  236.                                         // replace "dummy_path" with your actual storage path
  237.                                         StorageReference imageRef = storageReference.child("dummy_path/" + userId + "/" + hotelId + "/image.jpg");
  238.  
  239.                                         imageRef.putFile(selectedImageUri)
  240.                                                 .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
  241.                                                     @Override
  242.                                                     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
  243.                                                         // Image uploaded successfully, you can save its download URL if needed
  244.                                                         // Uri downloadUrl = taskSnapshot.getDownloadUrl();
  245.  
  246.                                                         Log.d("BookForm", "Image uploaded successfully");
  247.                                                         // Continue with saving other booking data to Firebase
  248.                                                         // ...
  249.  
  250.                                                         // Display a success message to the user
  251.                                                         Toast.makeText(BookForm.this, "Booking submitted.", Toast.LENGTH_SHORT).show();
  252.                                                     }
  253.                                                 })
  254.                                                 .addOnFailureListener(new OnFailureListener() {
  255.                                                     @Override
  256.                                                     public void onFailure(@NonNull Exception e) {
  257.                                                         Log.e("BookForm", "Image upload failed: " + e.getMessage());
  258.                                                         // Handle image upload failure here
  259.                                                     }
  260.                                                 });
  261.                                     }
  262.  
  263.                                     // store na under booking_info and generate ng unique id
  264.                                     DatabaseReference bookingsRef = databaseReference.child("booking_info").push();
  265.                                     String bookingId = bookingsRef.getKey();
  266.  
  267.                                     bookingsRef.child("userId").setValue(userId);
  268.                                     bookingsRef.child("fullName").setValue(fullName);
  269.                                     bookingsRef.child("checkInDate").setValue(checkInDate);
  270.                                     bookingsRef.child("checkOutDate").setValue(checkOutDate);
  271.                                     bookingsRef.child("adults").setValue(adults);
  272.                                     bookingsRef.child("children").setValue(children);
  273.                                     bookingsRef.child("contactNumber").setValue(contactNumber);
  274.                                     bookingsRef.child("email").setValue(email);
  275.                                     bookingsRef.child("roomPreference").setValue(roomPreference);
  276.                                     bookingsRef.child("yourGcashName").setValue(yourGcashName);
  277.                                     bookingsRef.child("yourGcashNumber").setValue(yourGcashNumber);
  278.                                     bookingsRef.child("referenceNumber").setValue(referenceNumber);
  279.                                     bookingsRef.child("userName").setValue(userName);
  280.                                     bookingsRef.child("hotelUserId").setValue(hotelUserId);
  281.  
  282.                                     Log.d("BookForm", "Booking data saved");
  283.                                 }
  284.                             }
  285.  
  286.                             @Override
  287.                             public void onCancelled(@NonNull DatabaseError hotelDatabaseError) {
  288.                                 Log.e("BookForm", "Hotel database error: " + hotelDatabaseError.getMessage());
  289.                             }
  290.                         });
  291.                     } else {
  292.                         Log.e("BookForm", "User data does not exist in the database");
  293.                     }
  294.                 }
  295.  
  296.                 @Override
  297.                 public void onCancelled(@NonNull DatabaseError databaseError) {
  298.                     Log.e("BookForm", "Database error: " + databaseError.getMessage());
  299.                 }
  300.             });
  301.         } else {
  302.             Log.e("BookForm", "User is not authenticated");
  303.         }
  304.     }
  305.  
  306.     private void showDatePickerDialog(final EditText editText) {
  307.         final Calendar calendar = Calendar.getInstance();
  308.         int year = calendar.get(Calendar.YEAR);
  309.         int month = calendar.get(Calendar.MONTH);
  310.         int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
  311.  
  312.         DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
  313.             @Override
  314.             public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
  315.                 // Adjust month index and set the selected date in the EditText
  316.                 String selectedDate = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year;
  317.                 editText.setText(selectedDate);
  318.             }
  319.         }, year, month, dayOfMonth);
  320.  
  321.         datePickerDialog.show();
  322.     }
  323.  
  324.     private boolean allFields() {
  325.         return !fullNameET.getText().toString().isEmpty() &&
  326.                 !contactNumberET.getText().toString().isEmpty() &&
  327.                 !emailET.getText().toString().isEmpty() &&
  328.                 !checkInDateET.getText().toString().isEmpty() &&
  329.                 !checkOutDateET.getText().toString().isEmpty() &&
  330.                 !roomPreferenceSpinner.getSelectedItem().toString().isEmpty() &&
  331.                 !yourGcashNameET.getText().toString().isEmpty() &&
  332.                 !yourGcashNumberET.getText().toString().isEmpty() &&
  333.                 !referenceNumberET.getText().toString().isEmpty();
  334.     }
  335.  
  336.     // Helper method to parse a date string to a Calendar object
  337.     private Calendar parseDate(String dateStr) {
  338.         Calendar calendar = Calendar.getInstance();
  339.         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
  340.         try {
  341.             Date date = sdf.parse(dateStr);
  342.             calendar.setTime(date);
  343.         } catch (ParseException e) {
  344.             e.printStackTrace();
  345.         }
  346.         return calendar;
  347.     }
  348.  
  349.     // Helper method to check if a date is within a date range
  350.     private boolean isCurrentDateInRange(Calendar currentDate, Calendar startDate, Calendar endDate) {
  351.         return (currentDate.compareTo(startDate) >= 0 && currentDate.compareTo(endDate) <= 0);
  352.     }
  353. }
  354.  
Tags: Android
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement