Display HTTP images in ImageView – Android kotlin
In this tutorial, we will show you how you can display HTTP images in your ImageView in your android app using Kotlin. We will be displaying this image “https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/stsci-01gfnn3pwjmy4rqxkz585bc4qh.png” in our image view.
Then create a file named “FetchImageFromInternet.kt” and write the following code in it:
package com.adnantech.myapp
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
@SuppressLint("StaticFieldLeak")
@Suppress("DEPRECATION")
class FetchImageFromInternet(var imageView: ImageView) : AsyncTask<String, Void, Bitmap?>() {
init {
// Toast.makeText(applicationContext, "Please wait, it may take a few minute...", Toast.LENGTH_SHORT).show()
}
override fun doInBackground(vararg urls: String): Bitmap? {
val imageURL = urls[0]
var image: Bitmap? = null
try {
val `in` = java.net.URL(imageURL).openStream()
image = BitmapFactory.decodeStream(`in`)
}
catch (e: Exception) {
Log.e("Error Message", e.message.toString())
e.printStackTrace()
}
return image
}
override fun onPostExecute(result: Bitmap?) {
imageView.setImageBitmap(result)
}
}
And this will be your image view:
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter" />
Then whenever you want to display an HTTP image, just write the following lines:
val imageView: ImageView = findViewById(R.id.imageView)
FetchImageFromInternet(imageView)
.execute("https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/stsci-01gfnn3pwjmy4rqxkz585bc4qh.png")
Run the app now and you will be able to view that HTTP image in your app. Check out our more tutorials on android.