Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Multiple images and wait for completion before returning, android and firebase

Hello I am trying to upload multiple images, wait for them to return, compile the download uri's into an object and send it back to my activity. I am using this as reference for upload, firebase. So far i have this

 private void saveStepWithImages(@NonNull Step step, Callback callback){

    if(step.getStepId() == null){
       Collection<Image> images =  step.getImages().values();

        List<Task<Uri>> taskArrayList= new ArrayList<>();
        for (Image i: images) {
            taskArrayList.add(uploadImageTask(new ImageUtils().StringToBitMap(i.getImageUrl()), i.getImageReference()));
        }

        Tasks.whenAll(taskArrayList).addOnCompleteListener(task -> {
            Uri downloadUri = task.getResult(); // throws an error because task.getResult is void
        });

    }else{
        updateStepInFirebase(step, callback);
    }

}

and in my upload images

private Task<Uri> uploadImageTask(final Bitmap bitmap, String prepend){
    final StorageReference ref = mStorageRef.child( prepend );

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] data = baos.toByteArray();

    UploadTask uploadTask = ref.putBytes(data);
    bitmap.recycle();

    return uploadTask.continueWithTask(task -> {
        bitmap.recycle();
        return ref.getDownloadUrl();
    });
}

Step is a custom object i created it contains a Map of images with a string as the key and the value being an image. My image class looks like this

public class Image implements Parcelable {

    private String imageUrl;
    private String imageReference;


    public void Image(){

    }

    //Setters and getters here;
}

Any suggestions would be really appreciated. Thanks!

like image 455
inhaler Avatar asked Aug 22 '18 00:08

inhaler


1 Answers

The key for solving this problem is to use Tasks's whenAllSuccess() method:

Returns a Task with a list of Task results that completes successfully when all of the specified Tasks complete successfully.

Insted of Tasks's whenAll() method:

Returns a Task that completes successfully when all of the specified Tasks complete successfully.

Please see more informations about Tasks class.

like image 98
Alex Mamo Avatar answered Oct 14 '22 21:10

Alex Mamo