When developing an application that uses Internet access, we often need to load an image from a URL and display it into ImageView
. To do that, we can use AsyncTask
.
Application should have Internet access. So, we need to request the INTERNET
permission in the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<application>
...
</application>
</manifest>
In the layout XML file, we added a ImageView
that will be used to display an image.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
We created a new class that extends AsyncTask
. The BitmapFactory.decodeStream()
method can be used to decode an input stream into a bitmap.
package com.example.app
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.widget.ImageView
import java.io.IOException
import java.net.URL
class LoadImageTask(private val imageView: ImageView) : AsyncTask<String, Void, Bitmap>()
{
override fun doInBackground(vararg urls: String): Bitmap?
{
try {
val stream = URL(urls[0]).openStream()
return BitmapFactory.decodeStream(stream)
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(bitmap: Bitmap?)
{
imageView.setImageBitmap(bitmap)
}
}
In the main activity, we execute a task that downloads an image from a specified URL and displays an image in the ImageView
. The task runs in the background and doesn't block the UI thread.
package com.example.app
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
LoadImageTask(myImageView).execute("https://picsum.photos/400")
}
}
Leave a Comment
Cancel reply