Load ImageView from URL in Android

Sometimes we need to show images in our Android application that are available in a remote server and can not be created as drawable resources. To load one of these images into an ImageView object, the image has to be turn from the URL into a bitmap. The following method solves this.

public boolean loadImageFromURL(String fileUrl, 
ImageView iv){
  try {

    URL myFileUrl = new URL (fileUrl);
    HttpURLConnection conn =
      (HttpURLConnection) myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();

    InputStream is = conn.getInputStream();
    iv.setImageBitmap(BitmapFactory.decodeStream(is));

    return true;

  } catch (MalformedURLException e) {
    e.printStackTrace();
  } catch (Exception e) {
    e.printStackTrace();
  }

  return false;
}

Remember to grant the permission “android.permission.INTERNET” in the AndroidManifest.xml file.

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

6 Comments

  1. Hi,
    I’d like to show url to imageView like you. I run that your code but it except NullPointerException in setImageBitmap. Do you think why it return null ?

    1. Hi, you have to check which object is null, maybe is the InputStream. Be sure than the URL is correct and the connection can access it.

  2. Not work…
    10-10 00:56:11.547: W/View(17835): requestLayout() improperly called by android.widget.ListView{425e55b0 VFED.VC. ……ID 0,0-604,1134 #102000a android:id/list} during layout: running second layout pass

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.