Sriram R
Sriram R

Reputation: 2229

Firebase Storage onSuccess called before upload is complete

I'm using Firebase storage to save photos. But my onSuccess is being called before the upload is complete

Error:

 java.lang.IllegalStateException: Task is not yet complete
        at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source)
        at com.google.android.gms.tasks.zzu.zzdq(Unknown Source)
        at com.google.android.gms.tasks.zzu.getResult(Unknown Source)
        at in.sekreative.sekreative.ui.auth.AuthActivity$uploadPhotoAndRegister$2.onSuccess(AuthActivity.kt:133)
        at in.sekreative.sekreative.ui.auth.AuthActivity$uploadPhotoAndRegister$2.onSuccess(AuthActivity.kt:24)
        at com.google.firebase.storage.zzj.zza(Unknown Source)
        at com.google.firebase.storage.zzaa.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6123)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Code

val storage = FirebaseStorage.getInstance().reference
storage.child("images/profile/${mAuth.currentUser?.uid}.jpg").putBytes(data)
        .addOnProgressListener {
            val progress = 100.0 * it.bytesTransferred / it.totalByteCount
            dialog.incrementProgress(progress.toInt())
        }
        .addOnSuccessListener {
            user.profile = it.storage.downloadUrl.result.toString()
            registerDataWithoutPhoto(user)
        }
        .addOnFailureListener {
            toast("Error uploading photo. You can update your profile pic later in the profile section.")
            registerDataWithoutPhoto(user)
        }

Why is the success listener being called before the task is complete?

FYI: It was working perfectly fine for a few times earlier. This was a sudden error.

Upvotes: 1

Views: 1033

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

it.storage.downloadUrl (javadoc) returns a Task that's complete only after the download URL for the reference is available. Your code isn't waiting for that task to complete. Instead, It's trying to immediately get the result, and that access is throwing an exception. Instead, you should use listeners on that Task like you are with the Task returned by putBytes.

Upvotes: 4

Related Questions