在上传完成之前调用Firebase存储onSuccess

时间:2018-05-13 18:57:37

标签: android firebase kotlin firebase-storage

我使用Firebase存储来保存照片。但我的onSuccess在上传完成之前被调用

错误:

 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)

代码

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)
        }

为什么在任务完成之前调用成功侦听器?

仅供参考:早前几次工作完全正常。这是一个突然的错误。

1 个答案:

答案 0 :(得分:3)

it.storage.downloadUrljavadoc)只有在参考的下载URL可用后才会返回完成的任务。您的代码不等待该任务完成。相反,它试图立即获得结果,并且该访问正在抛出异常。相反,您应该使用该任务上的侦听器,就像使用putBytes返回的任务一样。