Issue
I'm trying to load image from URL with this code :
@BindingAdapter("imageUrl")
fun ImageView.bindImage(imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build().toString()
val executor = Executors.newSingleThreadExecutor()
val handler = Handler(Looper.getMainLooper())
var image: Bitmap?
executor.execute {
try {
val `in` = URL(imgUri).openStream()
image = BitmapFactory.decodeStream(`in`)
handler.post {
this.setImageBitmap(image)
executor.shutdown()
}
} catch (e: Exception) {
Log.e("Tag", "onCreate: ${e.message}")
}
}
}
}
and this is the xml
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/iv_album_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
app:imageUrl="@{albumsObject.albumImage}"
android:src="@drawable/img_album_cover" />
it's worked fine .. but there's problems 1- when I run the emulator the laptop is heating up and the fan is getting very loud 2- if I scroll on the list of the recycler view the images binding slowly I can see the previous photo on the upcoming photo
Is there's a problem in this code ? or has any one have another way to load image from URL without using any third-party .. just Android SDK
Solution
I solved it with this code:
@BindingAdapter("imageUrl")
fun ImageView.bindImage(imgUrl: String?) {
if(this.drawable == null) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build().toString()
val uiHandler = Handler(Looper.getMainLooper())
thread(start = true) {
val bitmap = downloadBitmap(imgUri)
uiHandler.post {
this.setImageBitmap(bitmap)
}
}
}
}
}
fun downloadBitmap(imageUrl: String): Bitmap? {
return try {
val conn = URL(imageUrl).openConnection()
conn.connect()
val inputStream = conn.getInputStream()
val bitmap = BitmapFactory.decodeStream(inputStream)
inputStream.close()
bitmap
} catch (e: Exception) {
Log.e(ContentValues.TAG, "Exception $e")
null
}
}
- Check if it's not loaded yet to avoid more than one loaded.
- Add HTTPS to the URL.
- Create a thread to open an input stream connection and get the image bitmap.
- Create a handler to return to main thread and set image bitmap.
Answered By - Ahmed Mamdouh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.