NetworkImageView 总是抛出 NullPointerException cache.get(url) 从有效 URL 访问图像时不能为 null

NetworkImageView always throw a NullPointerException cache.get(url) must not be null when accessing an image from a valid URL

我目前正在尝试使用 Volley 的 NetworkImageView 加载图像:

<com.android.volley.toolbox.NetworkImageView
 android:id="@+id/nivCharacterDetailPhoto"
 android:adjustViewBounds="true"
 android:scaleType="fitCenter"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

在后台我是这样设置的:

private fun setImage(view: View) {
    val photoView = view.findViewById<NetworkImageView>(R.id.nivCharacterDetailPhoto)
    val imgLoader = VolleyRequestQueue.getInstance(view.context).imageLoader
    photoView.setImageUrl("https://i.imgur.com/7spzG.png", imgLoader)
}

但是每当我尝试使用它加载页面时,我都会收到一个 NullPointerException,即 cache.get(url) 不能为 null。 url 是有效的,所以我推测问题需要出现在 VolleyRequestQueue class 中。但是,此 class 与文档描述的 here 完全相同。 所以:

class VolleyRequestQueue constructor(context: Context) {
    companion object {
        @Volatile
        private var INSTANCE: VolleyRequestQueue? = null
        fun getInstance(context: Context) = INSTANCE ?: synchronized(this) {
            INSTANCE ?: VolleyRequestQueue(context).also {
                INSTANCE = it
            }
        }
    }
    val imageLoader: ImageLoader by lazy {
        ImageLoader(requestQueue, object : ImageLoader.ImageCache {
                private val cache = LruCache<String, Bitmap>(20)
                override fun getBitmap(url: String): Bitmap {
                    return cache.get(url)
                }
                override fun putBitmap(url: String, bitmap: Bitmap) {
                    cache.put(url, bitmap)
                }
            })
    }
    val requestQueue: RequestQueue by lazy {
        // applicationContext is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        Volley.newRequestQueue(context.applicationContext)
    }
    fun <T> addToRequestQueue(req: Request<T>) {
        requestQueue.add(req)
    }
}

我知道 url 是正确的字符串并且已设置。我使用调试器找到 cache.get(url) 语句,再次发现一个字符串被传递给了 cache.get(url) 函数。这次 url 包含的值类似于:“#W1440#H1916#S3https://i.imgur.com/7spzG.png”。但是我确实也注意到缓存完全是空的,这解释了为什么 cache.get(url) returns 为空。但是我假设(也许是错误的?)如果 none 存在于缓存中,使用这个默认实现它会尝试获取图像。

还有其他人 运行 关注这个问题吗?这似乎是一个非常基本的,但出于某种原因我就是想不通。

我 运行 宁 Android 11,API 30

所以,经过长时间的搜索,我终于找到了问题所在。文档对此不是很清楚但是:

override fun getBitmap(url: String): Bitmap {
    return cache.get(url)
}

应该是:

override fun getBitmap(url: String): Bitmap? {
    return cache.get(url)
}

由于缓存可能 return null 这导致该方法完全崩溃,因为它不允许 return 一个可为 null 的值。我不知道这是否仅使用 NetworkImageView,但如果有人 运行 再次遇到此问题,只需将 getBimap 方法 return 设为可为 null 的位图,它应该可以工作。