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"/>
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 ?
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.
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
It seems to me that the error has more to do with a list view
Does this really work?
Yes, it does, as long as you have internet connection.