android - BindingAdapter LiveData 第一个值始终为 null

标签 android kotlin android-livedata android-binding-adapter

我正在尝试在 BindingAdapter 函数中处理 LiveData 值(profilePicture: Bitmap),但第一个值始终是 null。绑定(bind)适配器是一个带有 ProgressBarImageViewViewSwitcher

像这样从 firebase 获取个人资料图片:

    val downloadPictureResult = MutableLiveData<Bitmap>()
    // ...
   fun downloadProfilePic(): LiveData<Bitmap?> {
        val imageRef = storage.getReference("images/$uid/profile/profile_picture.jpg")
        imageRef.getBytes(ONE_MEGABYTE).addOnCompleteListener { task ->
            if (task.isSuccessful) {
                //...
                downloadPictureResult.value =  responseBitmap
                //...
            } else {
                downloadPictureResult.value = null
                Log.d(TAG, task.exception?.localizedMessage)
            }
        }
        return downloadPictureResult;
    }

因为第一个值是null,第二个是预期的位图对象view.showNext()被调用了两次。但对我来说更重要的是要理解为什么 firstvalue 是 null 因为 setProfilePicture 方法会有更多的逻辑。

BindingAdapter 看起来像这样。

fun setProfilePicture(view: ViewSwitcher, profilePicture: Bitmap?) {
 Log.d("PPSS", profilePicture.toString())
    val imageView: ImageView = view[1] as ImageView
    imageView.setImageDrawable(view.context.getDrawable(R.drawable.account_circle_24dp))

    profilePicture.let { picture ->
        if (picture != null) {
            val rounded = RoundedBitmapDrawableFactory.create(view.resources, picture)
            rounded.isCircular = true
            imageView.setImageDrawable(rounded)
            view.showNext()
        } else {
            view.showNext()
        }
    }

Log:

2019-04-13 17:53:01.658 11158-11158/... D/PPSS: null
2019-04-13 17:53:02.891 11158-11158/... D/PPSS: android.graphics.Bitmap@8b6ecb8

最佳答案

当你定义一个LiveData时,即使它的类型不可为空,它的初始值也会为null:

val downloadPictureResult = MutableLiveData<Bitmap>()
// Here, downloadPictureResult.value is null

在您的情况下,downloadProfilePic() 返回的 LiveData 的值在图片下载之前将为空,这将在回调 内异步发生addOnCompleteListener:

fun downloadProfilePic(): LiveData<Bitmap?> {
    ...
    imageRef.getBytes(ONE_MEGABYTE).addOnCompleteListener { task ->
        ...
        // This happens asynchronously, likely after downloadProfilePic()
        // has already returned
        downloadPictureResult.value =  responseBitmap
        ...
    }

    return downloadPictureResult;
}

这就是为什么传递给你的适配器的第一个值是空的,因为当 downloadProfilePic 返回 downloadPictureResultdownloadPictureResult.value 仍然是空() 第一次。

关于android - BindingAdapter LiveData 第一个值始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667645/

相关文章:

Android应用程序在按钮单击时调用号码

javascript - 在 React Native 中授予权限

android - 在android中使用kotlin将字符串化的json转换为jsonArray

android - 如何在整洁的架构中实现购物车?

安卓机房 : How to combine data from multiple SQL queries into one ViewModel

java - Android WebView loadURL 崩溃应用程序?

java - Android Studio GCM 注册 ID 显示为空

kotlin - kotlin 中的 actor 在不同线程上运行时如何工作?

kotlin - 在 Kotlin 中锁定互斥锁的正确方法

Android MVVM - 如何让 LiveData 发出它拥有的数据(强制触发观察者)