Home » Android » android – Firebase all images are not stored-Exceptionshub

android – Firebase all images are not stored-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I am trying to store Images to firebase storage from Glide, but only the last image is being stored.

    for (i = 0; i < imageFileList.size(); i++) {
        StorageRef = mySTORAGE.getReferenceIMAGE_PATH + dataHolder.getTitle() + "/" + i + ".png");
        Glide.with(this).asBitmap().load(imageFileList.get(i).getAbsolutePath()).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                stream = new ByteArrayOutputStream();
                resource.compress(Bitmap.CompressFormat.JPEG, 20, stream);
                byte[] byteArray = stream.toByteArray();
                StorageRef.putBytes(byteArray);
            }
            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });
    }
How to&Answers:

I can only assume here that StorageRef is a class member, since you’re not showing where it’s defeined. If that’s the case, your loop is overwriting StorageRef at each interation, and only the last value will remain after the loop finishes. Since Glide is asynchronous, all of the callbacks will happen after the loop finishes, and they will all use the last value of StorageRef.

What you should do instead is make StorageRef a final local variable so it won’t get overwritten each time through the loop:

final StorageReference StorageRef =
    mySTORAGE.getReferenceIMAGE_PATH + dataHolder.getTitle() + "/" + i + ".png");