I'm uploading two files from an array on Firebase storage and want to get getDownloadUrl of both files but it returns only first element's uri. In this code mThumbUri
is always empty.
public class UploadingService extends JobIntentService implements UploadCallBacks {
private static final String CHANNEL_ID = "upload_channel";
private static final int JOB_ID = 1000;
private HashMap<String, String> values;
String mVideoUri = "";
String mThumbUri = "";
private FirebaseUser mUser;
private String postId = null;
//Firebase
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
public static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, UploadingService.class, JOB_ID, intent);
}
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
mUser = FirebaseAuth.getInstance().getCurrentUser();
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
if (intent.hasExtra(AppConstants.DATA)) {
values = (HashMap<String, String>) intent.getSerializableExtra(AppConstants.DATA);
hitVideoUploadApi();
}
}
/**
* method for video upload
*/
private void hitVideoUploadApi() {
postId = UUID.randomUUID().toString();
ArrayList<Uri> files = new ArrayList<>();
Uri VideoUri = Uri.fromFile(new File(values.get(AppConstants.VIDEO_PATH)));
Uri ThumbUri = Uri.fromFile(new File(values.get(AppConstants.THUMB_PATH)));
files.add(VideoUri);
files.add(ThumbUri);
Notification notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
Using a loop I'm upload both files on firebase storage and getting url in string mVideoUrl and mThumbUrl to upload these string to firebaseDatabase:
final int[] i = {0};
for (Uri uri : files) {
storageRef.child("PostData/" + UUID.randomUUID().toString()).putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
Uri uri = task.getResult();
i[0]++;
if (i[0] == 1) {
mVideoUri = uri.toString();
} else {
mThumbUri = uri.toString();
}
}
});
}
Here in addOnCompleteListener calling a fun to upload thse urls to firebase Realtime database
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
hitUploadPostApi(mVideoUri, mThumbUri, postId);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
notificationManager.cancel(NOTIFICATION_ID);
Toast.makeText(getApplicationContext(), "Error while Uploading", Toast.LENGTH_SHORT).show();
}
});
}
}