How to Load Any Image From URL Without Using Any Dependency in Android?
Last Updated :
05 Aug, 2021
Many applications display images from the internet using third-party APIs like Glide and Picasso to load images. This means that such applications partly depend on these services to keep themselves working fine. To make the application better, one should write their own code rather than depending on such services. In this article, we will show you how you can easily load images in your application without using any external service.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add Internet permission in the AndroidManifest.xml
Since images are in the form of URLs, the application will need internet permissions to parse the information.
XML
< uses-permission android:name = "android.permission.INTERNET" />
|
Step 3: Create an ImageView in the layout
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< ImageView
android:id = "@+id/imageView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true" />
</ RelativeLayout >
|
Step 4: Program to load image from URL and display in the ImageView
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val imageView = findViewById<ImageView>(R.id.imageView)
val executor = Executors.newSingleThreadExecutor()
val handler = Handler(Looper.getMainLooper())
var image: Bitmap? = null
executor.execute {
try {
val `in` = java.net.URL(imageURL).openStream()
image = BitmapFactory.decodeStream(`in`)
handler.post {
imageView.setImageBitmap(image)
}
}
catch (e: Exception) {
e.printStackTrace()
}
}
}
}
|
Output:
We can see that the image loads successfully. This means that the application works perfectly as intended.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...