skip to Main Content

The issue i am facing is that the image that it is saying not exist is the one that’s already in the app or display on the app also it’s already in the firebase realtime database

The code are:



 private void update(String hotelName, String hotelAddress, String hotelDescription, List<Uri> imageUris, String hotelContact,

                        String hotelEmail, List<String> roomTypes, String cancellationPolicy, String hotelId, String amenitiesHotel,

                        String gcashNumber, String gcashName, String reservationFee, double latitude, double longitude) {

        DatabaseReference hotelsRef = databaseReference.child("hotels");

        Query query = hotelsRef.orderByChild("user_id").equalTo(userId);

        query.addListenerForSingleValueEvent(new ValueEventListener() {

            @Override

            public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot dataSnapshot) {

                if (dataSnapshot.exists()) {

                    for (com.google.firebase.database.DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                        String hotelId = childSnapshot.getKey();

                        DatabaseReference hotelRef = hotelsRef.child(hotelId);

                        hotelRef.child("name").setValue(hotelName);

                        hotelRef.child("address").setValue(hotelAddress);

                        hotelRef.child("description").setValue(hotelDescription);

                        hotelRef.child("contact").setValue(hotelContact);

                        hotelRef.child("email").setValue(hotelEmail);

                        hotelRef.child("cancellationPolicy").setValue(cancellationPolicy);

                        hotelRef.child("amenities").setValue(amenitiesHotel);

                        hotelRef.child("gcashNumber").setValue(gcashNumber);

                        hotelRef.child("gcashName").setValue(gcashName);

                        hotelRef.child("reservationFee").setValue(reservationFee);

                        hotelRef.child("latitude").setValue(latitude);

                        hotelRef.child("longitude").setValue(longitude);

                        saveRoomTypes(hotelId, roomTypes);

                        if (!imageUris.isEmpty()) {

                            List<String> imageUrls = new ArrayList<>();

                            AtomicInteger uploadCount = new AtomicInteger(0);

                            // Use a CountDownLatch to wait for all uploads to complete

                            CountDownLatch latch = new CountDownLatch(imageUris.size());

                            for (int i = 0; i < imageUris.size(); i++) {

                                Uri imageUri = imageUris.get(i);

                                if (imageUri != null) {

                                    // Check if the file exists before attempting to upload

                                    if (fileExists(imageUri)) {

                                        StorageReference imageRef = storageReference.child("hotel_images/" + hotelId + "/image" + (i + 1));

                                        UploadTask uploadTask = imageRef.putFile(imageUri);

                                        uploadTask.addOnSuccessListener(taskSnapshot -> {

                                            imageRef.getDownloadUrl().addOnSuccessListener(downloadUri -> {

                                                String imageUrl = downloadUri.toString();

                                                imageUrls.add(imageUrl);

                                                if (uploadCount.incrementAndGet() == imageUris.size()) {

                                                    // All images uploaded, update the database

                                                    save(hotelId, imageUrls, hotelName, hotelAddress, hotelDescription, hotelContact,

                                                            hotelEmail, roomTypes, cancellationPolicy, amenitiesHotel, gcashNumber, gcashName, reservationFee, latitude, longitude);

                                                    // Release the latch when all uploads are complete

                                                    latch.countDown();

                                                }

                                            }).addOnFailureListener(e -> {

                                                Log.e("image upload", "Firebase Storage Error: " + e.getMessage());

                                                latch.countDown(); // Release the latch even if there's an error

                                            });

                                        }).addOnFailureListener(e -> {

                                            Log.e("image upload", "Error during upload: " + e.getMessage());

                                            latch.countDown(); // Release the latch even if there's an error

                                        });

                                    } else {

                                        Log.e(TAG, "Image file does not exist at Uri: " + imageUri.toString());

                                        latch.countDown(); // Release the latch in case of file not found

                                    }

                                } else {

                                    Log.e(TAG, "ImageUri is null. Handle this case accordingly.");

                                    latch.countDown(); // Release the latch in case of null Uri

                                }

                            }

                            try {

                                // Wait for all uploads to complete before proceeding

                                latch.await();

                            } catch (InterruptedException e) {

                                e.printStackTrace();

                            }

                        } else {

                            // If no images, update the database directly

                            save(hotelId, null, hotelName, hotelAddress, hotelDescription, hotelContact,

                                    hotelEmail, roomTypes, cancellationPolicy, amenitiesHotel, gcashNumber, gcashName, reservationFee, latitude, longitude);

                        }

                    }

                }

            }

            @Override

            public void onCancelled(@NonNull DatabaseError databaseError) {

                Log.e("update", "error" + databaseError.getMessage());

            }

        });

    }

    

    // Function to check if a file exists at the given Uri

    private boolean fileExists(Uri uri) {

        if (uri != null) {

            File file = new File(uri.getPath());

            return file.exists();

        }

        return false;

    }

I already check the rules etc..

Also if I upload the the second or more images it’s not updating or its not going to the storage or realtime database.
Thankyou

2

Answers


  1. You’re updating various fields such as name, address, etc. and also handling the upload of images to Firebase Storage.

    • Ensure that the fileExists() method is working as expected. If the imageUri is coming from the gallery or camera, it might not represent a local file path directly. You may need to handle different types of Uri schemes, such as content:// and file://.

    • The code uses a CountDownLatch to wait for all image uploads to complete. While this approach works, you might want to explore using Firebase’s Tasks.whenAllComplete() or Tasks.whenAllSuccess() for a more streamlined way to handle multiple asynchronous tasks.

    Please try this to might it solve your problem. Thanks.

    Login or Signup to reply.
  2. Add additional logging statements to trace the flow of execution and identify where the code might be failing.

    Log.d(TAG, "Checking file existence for Uri: " + imageUri.toString());
    if (fileExists(imageUri)) {
        Log.d(TAG, "File exists. Proceeding with upload.");
        // your ccode
    } else {
        Log.e(TAG, "Image file does not exist at Uri: " + imageUri.toString());
     
    

    latch.countDown();
    }

    also check the existence of a file like this:

    private boolean fileExists(Uri uri) {
        if (uri != null) {
            try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
                return inputStream != null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    

    Finally, make sure that your Firebase Storage rules allow read and write operations.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search