0

I need a solution to this problem where i need to get the string of the image url after it has retrive the url from the uploaded image. I know the asynchronous of Firebase and the system, but im finding a way, if there is a solution for this function to work,

public class FirebaseUtil {

    public FirebaseUtil() {
    }

    public String uploadLogo(final Context context, String uid, Uri image ){
        final String[] iref = {""};
        StorageTask uploadTask = null;
        if (uploadTask != null && uploadTask.isInProgress()){
            Toast.makeText(context, "File Uploading", Toast.LENGTH_SHORT).show();
        }
        else{
            ContentResolver cr = context.getContentResolver();
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            String extension = mime.getExtensionFromMimeType(cr.getType(image));
            StorageReference sref = FirebaseStorage.getInstance().getReference("StoreLogo");
            final StorageReference mStore = sref.child(uid+"."+extension);
            uploadTask = mStore.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    mStore.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            iref[0] = String.valueOf(uri);
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(context, "Could not upload store Image", Toast.LENGTH_SHORT).show();
                }
            });
        }
        return iref[0];
    }

}

PS: Please do not flag this question as duplicate as i know it is a Firebase synchronisation is different from android. I need a solution to this problem. If there is one.

novmbr29
  • 55
  • 6
  • Data is uploaded to Firebase asynchronously, and while this is happening your main code continues to run. This means that your `return iref[0]` runs before the `iref[0] = String.valueOf(uri)` does. If you place breakpoints on these lines and run in the debugger, you can verify this. The solution is always the same: all code that needs the URL must be inside the `onSuccess` or be called from there. For example of this, see https://stackoverflow.com/a/62412778 – Frank van Puffelen Oct 31 '20 at 13:26
  • Yes i completely get it but the problem is i cant return my sting value from inside the onsuccess(). how do i make it work? – novmbr29 Oct 31 '20 at 14:58

0 Answers0