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

时间:2021-03-29 14:09:48

标签: android kotlin android-volley

我目前正在尝试使用 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 类中。然而,这个类与文档描述的 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) 返回 null。但是我假设(可能是错误的?)使用这个默认实现,如果缓存中不存在图像,它会尝试获取图像。

有没有其他人遇到过这个问题?这似乎是一个非常基本的,但出于某种原因,我就是无法弄清楚。

我在 Android 11、API 30 上运行

1 个答案:

答案 0 :(得分:0)

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

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

应该是:

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

由于缓存可能返回 null,这导致方法完全崩溃,因为它不允许返回可为 null 的值。我不知道这是否只是使用 NetworkImageView,但如果有人再次遇到这个问题,只需让 getBimap 方法返回一个可为空的 Bitmap 就可以了。

相关问题