Android: How to load Image from URL in ImageView?

19 September 2012 By Nithya Vasudevan 121,497 views 18 Comments
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Project Description

  • In this tutorial, we will see how to load an image from URL into Android ImageView.
  • For downloading the image from URL and loading it in ImageView, we use AsyncTask.

Environment Used


Android Project

Create an Android project and name it as “ImageViewFromURL“.


Open res/values/strings.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
    <string name="hello">ImageView from URL</string>
    <string name="app_name">ImageViewFromURL</string>

XML layout file

This application uses XML layout file (main.xml) to display the ImageView.

Open main.xml file in res/layout and copy the following content.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:maxWidth="70dp" />



In src folder, create a new Class and name it as “ImageViewFromURLActivity” in the package “” and copy the following code.

From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below.



import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class ImageViewFromURLActivity extends Activity {

	public static final String URL = 
	ImageView imageView;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		imageView = (ImageView) findViewById(;

		// Create an object for subclass of AsyncTask
		GetXMLTask task = new GetXMLTask();
		// Execute the task
		task.execute(new String[] { URL });

	private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
		protected Bitmap doInBackground(String... urls) {
			Bitmap map = null;
			for (String url : urls) {
				map = downloadImage(url);
			return map;

		// Sets the Bitmap returned by doInBackground
		protected void onPostExecute(Bitmap result) {

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.
						decodeStream(stream, null, bmOptions);
			} catch (IOException e1) {
			return bitmap;

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
			} catch (Exception ex) {
			return stream;
  • Whenever we need to perform lengthy operation or any background operation we can use Asyntask which executes a task in background and publish results on the UI thread without having to manipulate threads and/or handlers.
  • In onCreate(), we create and execute the task to load image from url. The task’s execute method invokes doInBackground() where we open a Http URL connection and create a Bitmap from InputStream and return it.
  • Once the background computation finishes, onPostExecute() is invoked on the UI thread which sets the Bitmap on ImageView.

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client.
For Gingerbread and later, HttpURLConnection is the best choice.


Define the activity in AndroidManifest.xml file. To access internet from Android application set the android.permission.INTERNET permission in manifest file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <!-- Allows applications to open network sockets. -->
    <uses-permission android:name="android.permission.INTERNET" />

        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Run your application

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , ,

  • jay

    Very Nice Thnx :)……….

  • kannan

    very nice but i want how to set two different imageview link when am press image automatically load browser, download file(not image some other file am specify url into that imagebackground) plz help me

  • Deepesh Bhati

    Thanks for this tutorial…..

  • jason

    Nice sample . It works perfectly. If possible then add feature to download source code

  • Bruno

    Really useful…. Thanks a lot….

  • Stir-Fried Code

    This tutorial really helped me; I’d had nothing but failures trying to get an image to load from a url. This tutorial gave me my first success. Thanks!

  • priya

    Helped alot as a beginner…:)
    Thanks :)

  • Abhishek Sinari

    Thanx a lot for code. But I want to use it to load for multiple images. Please mail me the code @ [email protected]

    • getsuga

      btw, if you got replay from the admin.. can you forward it to me too?? because i want to know how to use in multiple imange..
      here my mail : [email protected]

  • Yoga Murthy.s

    great code helped me a lot in making the first app

  • Yoga Murthy.s

    Hey all, this code actually gives an crash in application whenever there is no internet connectivity in the device. could you please add the exception code to the tutorial?

  • getsuga

    btw, can you tell me how to load text from URL in this project too?? and if you don’t mind in multiple text and image, not just one text and image..

  • az

    it gives me an error in line 73 of ImageViewFromURLActivity!
    brcause I have no class named URL!
    please help me how to make it

  • Pingback: Displaying Google+ profile picture using intents | Zehr Answers

  • WilczurZnahor

    Hi, I am using this code, but when creating bitmap

    bitmap = BitmapFactory.
    decodeStream(stream, null, bmOptions);

    — SkImageDecoder::Factory returned null

    any advices?

  • Sourabh Jain