Open In App

How to Load SVG From URL in Android ImageView with Kotlin?

Improve
Improve
Like Article
Like
Save
Share
Report

Many websites use images of different types within their project. They may be SVG, png as well as jpeg image format. It is easy to load png and jpeg images within the android application using Picasso and Glide image loading library. If you want to load an SVG image within your application from the image URL we have to make an HTTP request. In this article, we will be building a simple application in which we will be simply loading an SVG image from the image URL. 

Note: If you are looking to implement SVG image from URL within your android application using Java. Check out the following article: How to load SVG image from URL in Android using Java

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. Note that select Kotlin as the programming language.

Step 2: Before moving to the coding part add these two dependencies in your build.gradle

Go to Gradle Scripts > build.gradle (Module: app) section and add the following dependencies and click the “Sync Now” on the above pop-up. Add these two dependencies.

implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.pixplicity.sharp:library:1.1.0'

Step 3: Add internet permission to your AndroidManifest.xml file

Navigate to the app > manifest and add internet permission.

XML




<uses-permission android:name="android.permission.INTERNET" />


Step 4: Working with the activity_main.xml file

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. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!-- Textview to display the heading of the app-->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:padding="5dp"
        android:text="SVG Image from URL"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--image view for displaying our svg image-->
    <ImageView
        android:id="@+id/idIVImage"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true" />
 
</RelativeLayout>


Step 5: Creating a new Java/Kotlin class for Utils

Navigate to the app > java > your app’s package name > Right-click on it > New Java/Kotlin class and name your class as Utils and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.R
import android.content.Context
import android.widget.ImageView
import com.pixplicity.sharp.Sharp
import okhttp3.*
import java.io.IOException
import java.io.InputStream
 
class Utils {
     
    // on below line we are creating a variable for http client.
    private var httpClient: OkHttpClient? = null
 
    // on below line we are creating a function to load the svg from the url.
    // in below method we are specifying parameters as context,
    // url for the image and image view.
    fun fetchSVG(context: Context, url: String, target: ImageView) {
        // on below line we are checking
        // if http client is null
        if (httpClient == null) {
            // if it is null on below line
            // we are initializing our http client.
            httpClient =
                OkHttpClient.Builder().cache(Cache(context.cacheDir, 5 * 1024 * 1014) as Cache)
                    .build() as OkHttpClient
        }
         
        // on below line we are creating a variable for our request and initializing it.
        var request: Request = Request.Builder().url(url).build()
         
        // on below line we are making a call to the http request on below line.
        httpClient!!.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                // we are adding a default image if we gets any
                // error while loading image from url.
                target.setImageResource(R.drawable.stat_notify_error)
            }
 
            @Throws(IOException::class)
            override fun onResponse(call: Call?, response: Response) {
                // sharp is a library which will load stream which we generated
                // from url in our target image view.
                val stream: InputStream = response.body()!!.byteStream()
                Sharp.loadInputStream(stream).into(target)
                stream.close()
            }
        })
    }
 
}


Step 6: Working with the MainActivity.kt file

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




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating
    // variable for image view.
    lateinit var imageView: ImageView
     
    // on below line we are creating a string
    // variable for our url of the svg image.
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are
        // initializing our image view.
        imageView = findViewById(R.id.idIVImage)
         
        // on below line we are calling utils
        // class to load the image from image url.
        Utils().fetchSVG(this,url,imageView)
    }
}


Now run your application to see the output of it. 

Output: 

Output

 



Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads