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 >): ArrayAdapter(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