android - 如何按arraylist中的顺序将多个文件上传到firebase数据库?
问题描述
我正在尝试将多个图像添加到 firebase,但它似乎没有按顺序上传。我相信 myUrlList 的添加取决于上传到服务器的顺序。有什么方法可以将 myUrlsList 与 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);
解决方案
即使您使用循环,理论上,图像的上传也应该按照迭代的顺序,您无法知道实际将每个图像分别上传到 Firebase 存储需要多少时间。正如@DougStevenson 在他的评论中提到的那样,您正在“并行”上传所有内容。因此,即使较小的图像位于较大的图像之后,较小尺寸的图像也可以比较大尺寸的图像上传得更快,因为上传所需的时间更短。
解决这个问题的解决方案是等到一张图片上传完成后,在上一张图片上传完成后开始下一次上传。这通常是通过递归来完成的,使用一个调用自身的方法。
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
}
}
});
}
}
首先,使用uploadImageToFirebaseStorage()
. 上传图像后,该方法将检查是否还有更多工作需要完成,如果是,则重新调用自身。
推荐阅读
- swift - 如何使用变量的字符串值来更改特定对象的文本
- java - 尝试使用正则表达式查找后跟逗号的数字的出现
- linq - 使用 linq lambda 表达式在同一个表中求和
- jsf - 表达式语言,选择方法,根据值
- android - 如何在 google play 应用描述中添加顶级功能
- python - Python - 如何计算列表中的列表,以及它们之间的算术
- android - 使用 ButterKnife 会使应用程序变慢吗?
- plsql - 如何改进 pl-sql 过程代码,100k 记录需要 2 小时
- python - 用于投票的 Django 表单
- ruby-on-rails - 尝试构建嵌套评论系统 Rails 5