Reputation: 15
I'm trying to add multiple images to firebase, but it seems like it doesn't upload in order. I believe myUrlList gets added depending on the order of getting uploaded to the server. Is there any way I can sort myUrlsList same as imageUrlList?
for(int i=0; i< imageUriList.size(); i++){
final StorageReference filereference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUriList.get(i)));
uploadTask = filereference.putFile(imageUriList.get(i));
uploadTask.continueWithTask(new Continuation() {
@Override
public Object then(@NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filereference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
myUrlList.add(myUrl);
Upvotes: 0
Views: 1106
Reputation: 138934
Even if you are using a loop and theoretically, the upload of the images should be in the order of the iteration, you cannot know how much it will take to actually upload each image to the Firebase Storage separately. As @DougStevenson mentioned in his comment, you are uploading everything in "parallel". So an image of a smaller size can be uploaded much faster than an image of a bigger size, even if the smaller image is positioned right after the larger image, as it will take a smaller amount of time to be uploaded.
The solution to solve this issue is to wait until an image is uploaded and start the next upload, right after the upload of the previous image completes. This is typically done with recursion, with a method that invokes itself.
private void uploadImageToFirebaseStorage() {
if (imageUriList.size() > 0) {
Uri imageUri = imageUriList.get(0);
StorageReference filereference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
imageUriList.remove(0);
uploadTask = filereference.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
@Override
public Object then(@NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filereference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
myUrlList.add(myUrl);
uploadBeerImageToFirebaseStorage(); //Call when completes
}
}
});
}
}
First, kick it off with uploadImageToFirebaseStorage()
. Once an image is uploaded, the method will check if there's more work that should be done, and reinvokes itself if that's the case.
Upvotes: 2
Reputation: 89
get the name from arraylist create new handler and execute runnable, Now every time when upload execute it create new runnable for different file and then upload file as your requirement.
Upvotes: 0