简体   繁体   中英

Why my image's data url is not saving in firebase firestore?

I am working on an application where i need to write multiple images to firebase storage and save their URL to firestore database. I am able to writing the data to storage but its url is not saving in the firestore databse. please guide me how can i achieve that where i am doing it wrong.

my code

    activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {

            if (result.getResultCode() == RESULT_OK && null != result.getData()) {

                if (result.getData().getClipData() != null) {

                    //this part to get multiple images
                    int countOfImages = result.getData().getClipData().getItemCount();
                    for (int i = 0; i < countOfImages; i++) {
                     // limiting the number of images picked up from gallery
                        if (uri.size() < 11) {
                            Uri imageuri = result.getData().getClipData().getItemAt(i).getUri();
                            uri.add(imageuri);
                            String imageName = getfilename(imageuri);

                            StorageReference mref =  reference.child("RoomsImages").child(imageName);
                          
                            mref.putFile(imageuri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                    if (task.isSuccessful()) {
                                                saveImageDataToFirestore();
                                Toast.makeText(MainActivity.this, "Data Added to firebase storage", Toast.LENGTH_SHORT).show();


                                        mref.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Uri> task) {
                                                savedImagesUri.add(task.getResult().toString());

                                            }
                                        });
                                    }

                                }
                            });
                        } else {

                            Toast.makeText(MainActivity.this, "Not Allowed more than 11 images", Toast.LENGTH_SHORT).show();

                        }

                    }
                    //this to notify
                    adapter.notifyDataSetChanged();
                    rentSell3Binding.totalphotos.setText("Photos (" + uri.size() + ")");

                } 

Firestore code

   private void saveImageDataToFirestore() {

    Map<String, Object> dataMap = new HashMap<>();

    //Below line of code will put your images list as an array in firestore
    dataMap.put("images", savedImagesUri);
    
    collectionReference.add(dataMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Toast.makeText(MainActivity.this, "Images Uploaded and saved successfully", Toast.LENGTH_SHORT).show();

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            //  coreHelper.createAlert("Error", "Images uploaded but we couldn't save them to database.", "OK", "", null, null, null);
            Toast.makeText(MainActivity.this, "Images uploaded but we couldn't save them to database.", Toast.LENGTH_SHORT).show();
            Log.e("MainActivity:SaveData", e.getMessage());
        }
    });
}

You're writing the entire array of image URLs to Firebase each time an image upload completes, but are doing so before you get the download URL if the latest upload. So that means you'll end up missing the download URL for the last image you upload.

To fix this move the code to write to Firestore into the onComplete that runs after the download URL is gotten:

mref.putFile(imageuri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        if (task.isSuccessful()) {
            Toast.makeText(MainActivity.this, "Data Added to firebase storage", Toast.LENGTH_SHORT).show();

            mref.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    savedImagesUri.add(task.getResult().toString());
                    saveImageDataToFirestore(); // 👈
                }
            });
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM