class ImageDownloader (private val url: String, private val imageView: ImageView, private val progressBar: ProgressBar) : Handler.Callback { private val handler = Handler(Looper.getMainLooper(), this) override fun handleMessage(msg: Message): Boolean { if (msg.what == 0) { imageView.setImageBitmap(msg.obj as Bitmap) progressBar.visibility = View.GONE } else if (msg.what == 1) { progressBar.progress = msg.arg1 } return true } fun download() { Thread { val bitmap = downloadImageFromUrl(url) handler.sendMessage(handler.obtainMessage(0, bitmap)) }.start() } private fun downloadImageFromUrl(url: String): Bitmap? { var bitmap: Bitmap? = null try { val urlConnection = URL(url).openConnection() urlConnection.connect() val inputStream = urlConnection.inputStream val totalSize = urlConnection.contentLength val data = ByteArray(1024) var downloadedSize = 0 var bufferLength: Int while (inputStream.read(data).also { bufferLength = it } != -1) { downloadedSize += bufferLength val progress = (downloadedSize * 100 / totalSize) handler.sendMessage(handler.obtainMessage(1, progress, 0)) bitmap = BitmapFactory.decodeByteArray(data, 0, bufferLength) } inputStream.close() } catch (e: Exception) { Log.e("ImageDownloader", "Error downloading image", e) } return bitmap } } 报出Process: com.example.imagedownloader, PID: 4842 java.lang.NullPointerException: null cannot be cast to non-null type android.graphics.Bitmap错误 修改代码
时间: 2024-02-10 14:07:15 浏览: 102
在 `downloadImageFromUrl` 函数中,应该将 `BitmapFactory.decodeByteArray` 转换成可空类型,以避免在无法解码字节数组时抛出 `NullPointerException`。修改后的代码如下:
```
private fun downloadImageFromUrl(url: String): Bitmap? {
var bitmap: Bitmap? = null
try {
val urlConnection = URL(url).openConnection()
urlConnection.connect()
val inputStream = urlConnection.inputStream
val totalSize = urlConnection.contentLength
val data = ByteArray(1024)
var downloadedSize = 0
var bufferLength: Int
while (inputStream.read(data).also { bufferLength = it } != -1) {
downloadedSize += bufferLength
val progress = (downloadedSize * 100 / totalSize)
handler.sendMessage(handler.obtainMessage(1, progress, 0))
bitmap = BitmapFactory.decodeByteArray(data, 0, bufferLength)?.let { it } // 加上安全转换
}
inputStream.close()
} catch (e: Exception) {
Log.e("ImageDownloader", "Error downloading image", e)
}
return bitmap
}
```
阅读全文