I'm a beginner in Kotlin and Android Studio and I would like to request for help to resolve this question:
- Download an image from the URL;
- Create Adapter module to receive bitmap;
- Show image through
ImageView
object
- I managed to resolve the first item with this simpler method. The next step is to improve with some library, but it's working.
private fun downloadImage(item: Item) = Thread {
val imageConnection = URL(imageItem.url).openConnection() as HttpURLConnection
try {
if (photosConnection.responseCode == HTTP_OK) {
runOnUiThread {
val bitmap = BitmapFactory.decodeStream(photosConnection.inputStream)
activityMainBinding.objImageView.apply {
// Implementar o novo Adapter
}
}
} else {
runOnUiThread{
Toast.makeText(this, " Deu erro !!!", Toast.LENGTH_SHORT).show()
}
}
} catch ( e: Exception) {
e.printStackTrace()
} finally {
imageConnection.disconnect()
}
}.start()
- Create adapter module
I tried to make this adapter which is what I had as a reference. But inheriting from ArrayAdapter
I understood that not compatible with Bitmap type. I was also unsure about the object (android.R.layout
) normally I use (android.R.layout.simple_list_item_1
)when they are String list applications. But in this case I didn't find similar, for example (android.R.layout.image
).
class ImageAdapter (
private val activityContext: Context,
private val imageList: MutableList<Bitmap>
): ArrayAdapter<Bitmap>(activityContext, android.R.layout.simple_list_item_1, photosList) {
private data class ImageHolder( val imageVw: ImageView )
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val imageView = convertView ?: LayoutInflater.from(activityContext)
.inflate(android.R.layout.simple_list_item_1,parent,false).apply {
tag = ImageHolder(findViewById(android.R.id.text1))
}
(imageView.tag as ImageHolder)imageVw.setImageBitmap = imageList[position]
return imageView
}
}
I appreciate any help
I'll try to keep it simple as possible
Use library to download image, e.g. glide, it's really simple and handling all the other things like url connection, thread and caching image.
For this you should use
RecyclerView
with creating your subclass ofRecyclerView.Adapter
.Also done with the glide library.
Now for code, this is Activity layout, you have to put recyclerView somewhere to show the list with images, in my example
activity_image_adapter.xml
:And also create layout for image items, in my exampe
item_image.xml
Next step you need to create custom adapter for the recyclerView:
Now put it all together in activity code:
After complete all part you will be able to show images, e.g like in the picture