Kotlin 为什么saveProfile方法中的变量dowloadUrl返回null?
下面的代码显示了我用来获取变量downloadUrl的firebase存储上载任务,downloadUrl在日志中打印时不为null,但是当我调用函数saveProfile时,它返回null,为什么Kotlin 为什么saveProfile方法中的变量dowloadUrl返回null?,kotlin,Kotlin,下面的代码显示了我用来获取变量downloadUrl的firebase存储上载任务,downloadUrl在日志中打印时不为null,但是当我调用函数saveProfile时,它返回null,为什么 var downloadUrl: String? = null fun upload(bytes: ByteArray) { val storageReference = FirebaseStorage.getInstance().reference .child(
var downloadUrl: String? = null
fun upload(bytes: ByteArray) {
val storageReference = FirebaseStorage.getInstance().reference
.child(
"images/users/${FirebaseAuth.getInstance().currentUser!!.uid}/profile_image"
)
val metadata = StorageMetadata.Builder()
.setContentType("image/jpg")
.setContentLanguage("en")
.build()
storageReference.putBytes(bytes, metadata).addOnSuccessListener {
model.listener!!.progressBarGone()
model.listener!!.toast("Uploaded Successfully")
val urlTask = it.storage.downloadUrl
while (!urlTask.isSuccessful);
this.downloadUrl = urlTask.result.toString()
Log.d("Upload", "DownloadUrl $downloadUrl")
这是saveProfile函数
fun saveProfile() {
val user = User()
if (model.name.isNullOrEmpty() || model.phone.isNullOrEmpty()) {
model.listener!!.toast("Fields cannot be empty")
return
}
if (downloadUrl.isNullorEmpty()) {
log.d(TAG, "URL empty")
}
user.name = model.name
user.phone = model.phone
user.profile_image = downloadUrl
当你打电话的时候
this.downloadUrl = urlTask.result.toString()
将
downloadUrl
分配给绑定到传递给addOnSuccessListener
的lambda的对象,而不是全局downloadUrl
。为了快速修复,我建议您将globaldownloadUrl
重命名为其他不会被隐藏的名称 仍在传递nullvar url:String?=null
然后url=urlstask.result.toString()
您是否实际在saveProfile
中使用url
?是的,我正在保存它,用户对象、姓名和电话都会被保存。如果您在从storageReference.putBytes(字节,元数据)回调之前调用saveProfile
,则会触发addOnSuccessListener,url
将不会被设置。如何调用saveProfile
?