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() { 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 .

Posted in Android Tagged

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *