0

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();
            }
        });
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Are you certain that the task is successful? You should add a condition `if (task.isSuccessfull())` in your `onComplete` callbacks to make sure you are not proceeding with error. – Christilyn Arjona Dec 18 '19 at 21:39
  • In which place do you say that `mThumbUri` is empty? Inside the `onComplete` method? – Alex Mamo Dec 19 '19 at 08:43
  • yea it task is working successfully and uploading both files but getting getDownloadUrl just of first file which is mVideoUrl @Christilyn – Muhammad Hamza Dec 19 '19 at 19:12
  • `Uri uri = task.getResult(); i[0]++; if (i[0] == 1) { mVideoUri = uri.toString(); } else { mThumbUri = uri.toString(); }` here in else **uri.tostring** is empty which i'm storing in**mThumbUri** @AlexMamo – Muhammad Hamza Dec 19 '19 at 19:16
  • **[This](https://stackoverflow.com/questions/53299915/how-to-get-offline-uploaded-file-download-url-in-firebase/53300660#53300660)** is the way you should get the download url. – Alex Mamo Dec 20 '19 at 07:44

1 Answers1

0

What you can do once the upload is complete you can check the firebase storage to get all the URL of files considering you know the names of the file. I wrote this 1 year back and it worked then.

enter image description here

inside the [child()] method you have to put the name of the file. Also, remember firebase is asynchronous.

Now coming to your code what I think is causing the problem is

Initially i[0]=0; 1 file upload complete successfully i[0]=1, 2 file upload complete successfully i[0]=2.

But you are checking [if(i[0]==1)] {whereas 2nd time 'i' is two}

rohan ghosh
  • 159
  • 6
  • if (i[0] == 1) works when i++ and for 2nd file i have used else{ ....} so it should workif i is 0 or 2 – Muhammad Hamza Dec 18 '19 at 20:24
  • Hi Rohan. Please replace your image with the text equivalant - if someone wishes to you your code, they won't want to transcribe it from the image. Thanks! – halfer Dec 18 '19 at 21:57