How do you use an image referenced by URL in an ImageView
?
-
1try out this one http://stackoverflow.com/questions/14332296/how-to-set-image-from-url-using-asynctask/15797963#15797963 – comeGetSome Apr 07 '13 at 16:27
-
2Use Picasso...http://stackoverflow.com/a/23865531/3535286 – chiragkyada May 26 '14 at 08:12
-
public class ImageDownloader { private final Executor executor = Executors.newSingleThreadExecutor(); public void download(String url, Consumer
onSuccess, Consumer – Sarsaparilla Dec 02 '20 at 03:56onError) { Handler handler = new Handler(); executor.execute(() -> { try (InputStream in = new URL(url).openStream()) { Bitmap result = BitmapFactory.decodeStream(in); handler.post(() -> onSuccess.accept(result)); } catch (Exception e) { handler.post(() -> onError.accept(e)); } }); } }
23 Answers
From Android developer:
// show The Image in a ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Make sure you have the following permissions set in your AndroidManifest.xml
to access the internet.
<uses-permission android:name="android.permission.INTERNET" />

- 4,175
- 2
- 25
- 33

- 7,359
- 2
- 13
- 3
-
43This is awesome. And should be much higher on the list. The asynctask allows this to load without freezing up the UI! – Kyle Clegg Jun 03 '12 at 05:26
-
3AsyncTasks uses a serial executor, meaning each image will load one at a time and not do parallel thread loading. – Blundell Apr 28 '13 at 10:27
-
11The input stream is not closed in your example. Best done in the finally block of your try/catch. – Risadinha Sep 03 '13 at 10:58
-
@Blundell not a problem really because your com is for the most part serial too. Try downloading two big files on your desk. Each slows down the other. In the end it will take just as long to get the data. – baash05 Sep 28 '13 at 13:43
-
perfect, thank you. only thing I added was closing the stream after getting the bimtap. – Guy Jul 11 '14 at 08:00
-
When I use this code to download Google Map static in ImageView, it is working well with Wifi, but with 3G, I have a: java.io.FileNotFoundException: http://maps.google.com/maps/api/staticmap?center=19.3153234,-98.8829254&zoom=17&size=480x160&sensor=false&markers=color:red%7C19.3153234,-98.8829254 off course, link is opening, so I don't understand well – Juliatzin Oct 28 '14 at 17:50
-
Sorry for the bump but I think that it's worth noting that even if the destination URL is a .jpg file and not a .png, the code would still work. – Razgriz Apr 03 '15 at 02:42
-
How can you do memory management in this setup. If there is a fullscreen view where these images are downloaded, and the user keeps swiping, can multiple Bitmap objects be created at the same time (one for each imageview) causing an OOM error? Some devices have small VMs and a full screen image can take up a lot of memory. – wislo May 16 '15 at 17:46
-
tanks @Android Developer but i am 3 image in execute crash app this method only use one image please help me to use 3 or more image – Mir Hussain Oct 23 '15 at 09:31
-
2Is this method still relevant? I am a bit confused about the OnClick() method and its purpose – tccpg288 Feb 11 '16 at 02:56
-
1this is strange, I get no error but the resulting mIcon11 is always null. I also checked if "in" is also null but no, it's not null. Something must be going wrong with BitmapFactory.decodeStream(in) – Roni Tovi Apr 27 '16 at 17:55
-
Please update the sample URL to start with HTTPS (https://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png). By using the HTTP it always returns NULL and it took me a long time before finding out the issue was so simple. – Vitor Siqueira Jan 02 '19 at 22:34
-
Grossly out of date and inadequate. Doing image fetching is not a trivial thing; please use a library. – Melllvar May 24 '20 at 05:50
1. Picasso allows for hassle-free image loading in your application—often in one line of code!
Use Gradle:
implementation 'com.squareup.picasso:picasso:(insert latest version)'
Just one line of code!
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
2. Glide An image loading and caching library for Android focused on smooth scrolling
Use Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
// For a simple view:
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);
3. fresco is a powerful system for displaying images on Android applications. Fresco takes care of image loading and display, so you don't have to.
4. Coil is an image loading library for Android backed by Kotlin Coroutines.
implementation("io.coil-kt:coil:2.3.0")
To load an image into an ImageView
, use the load extension function:
imageView.load("https://example.com/image.jpg")

- 22,633
- 10
- 99
- 115

- 3,585
- 3
- 17
- 18
-
3So if the url is localhost,means the image are in the developing system local server database like xampp ,still i m able to get the image from the url =. – blackjack Jun 09 '14 at 10:31
-
3@blackjack -- localhost from the app would be the smartphone itself. To access your developing system, the smartphone and your developing system will have to be in same network and you'd have to use the IP address of your developing system in that network. – Ridcully Feb 15 '15 at 07:02
-
1
-
1@chiragkyada i try with this code Picasso.with(context).load(url).into(button_view); but it`s show error for : into(button_view) – mahdi Mar 11 '15 at 13:46
-
-
1
-
1Except when fit() causes images to randomly fail for no reason – Juan Carlos Ospina Gonzalez Jul 25 '16 at 12:29
-
I have somename.xml file in the db and i am loading it into a Imageview using Picasso but my onBitmapFailed() called everytime... I am using Picasso – Aman Verma Sep 23 '17 at 20:08
-
1The Picasso example seems obsolete right now with version 2.71828 There's no "with" method. – Fran Marzoa Mar 07 '18 at 19:51
-
-
Picasso doesn't work anymore, the download link on their website gives a 404 error. – Donald Duck Aug 10 '21 at 08:56
You'll have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView

- 21,163
- 21
- 69
- 92
-
127u r right. but just these 3 lines helps to solve the problem. URL newurl = new URL(photo_url_str); mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); profile_photo.setImageBitmap(mIcon_val); thanks for ur reply. – Praveen Mar 19 '10 at 08:57
-
2For URL - import java.net.URL; private static final int IO_BUFFER_SIZE = 4 * 1024; what was the last one? – Steve Mar 19 '10 at 12:07
-
12See the code here: http://stackoverflow.com/questions/3118691/android-make-an-image-at-a-url-equal-to-imageviews-image – OneWorld Sep 24 '10 at 08:36
-
@SACPK you should write your comment as an answer so it can get voted up – Jim Wallace Oct 22 '11 at 23:27
-
-
The async loading method from android-developer / philipp is much better than this synchron loading – Henry Jul 11 '13 at 10:49
-
My post was made in 2010, the post you talk about was made in 2012. A bunch of API's have most likely been added since then. – Steve Jul 12 '13 at 11:15
-
@steve Thank... But there is some problems. Although i change 'closeStream(in);' to 'in.close();' but I don't know what to do with 'copy(in, out);' ??? – ABS May 10 '14 at 09:40
-
@AliBagheriShakib Hey Ali - sorry to be the bearer of bad news but I wrote this answer around 4 years ago on android 1.6. I'm very much out of date now ! – Steve May 10 '14 at 11:23
-
1Hey @steve don't underestimate yourself! :) I found implementation of the pseudo code part. This line "copy(in, out)" must replaced with these : int bytesRead; byte[] buffer = new byte[IO_BUFFER_SIZE]; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } – ABS May 10 '14 at 13:49
-
The method copy(InputStream, BufferedOutputStream) is undefined for the typev – Francisco Corrales Morales Dec 01 '14 at 15:22
-
Anyway people ask my comment to post it as answer. i am posting.
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
-
-
21
-
2For people having issues with "Malformed URL Exeption", surround the lines above in a try/catch. http://stackoverflow.com/a/24418607/2093088 – Riot Goes Woof Jun 23 '15 at 16:28
-
1
I wrote a class to handle this, as it seems to be a recurring need in my various projects:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an ImageView with an image that is found at a URL.
The sample will do a Google Image Search and load/show the results asynchronously.
UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

- 173,507
- 49
- 363
- 364

- 2,972
- 28
- 31
-
-
-
1It seems we need to use this one instead https://github.com/koush/ion as UrlImageViewHelper has been deprecated as shown on the github project's page at https://github.com/koush/UrlImageViewHelper. – Svetoslav Marinov Jan 12 '15 at 15:34
The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.
To use an asynctask add this class at the end of your activity:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
And call from your onCreate() method using:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
The result is a quickly loaded activity and an imageview that shows up a split second later depending on the user's network speed.

- 5,442
- 8
- 39
- 50

- 38,547
- 26
- 130
- 141
You could also use this LoadingImageView view to load an image from a url:
http://blog.blundellapps.com/imageview-with-loading-spinner/
Once you have added the class file from that link you can instantiate a url image view:
in xml:
<com.blundell.tut.LoaderImageView
android:id="@+id/loaderImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
image="http://developer.android.com/images/dialog_buttons.png"
/>
In code:
final LoaderImageView image = new LoaderImageView(this, "http://developer.android.com/images/dialog_buttons.png");
And update it using:
image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
-
Nice sample, but I don't believe this is thread safe. I'm trying to use it in an Async onPostExecute, however the onPostExecute can sometimes end before the callback is received rendering a null image. – Jimmy Jan 21 '12 at 03:34
-
This manages it's own thread. So why not have your ASyncTask call back to the UI when it has finished, with the url you want. That way you don't have threads spawning threads. – Blundell Aug 11 '12 at 11:19
The best modern library for such a task in my opinion is Picasso by Square. It allows to load an image to an ImageView by URL with one-liner:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

- 5,000
- 2
- 30
- 50
public class LoadWebImg extends Activity {
String image_URL=
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView bmImage = (ImageView)findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex)
{
}
return inputStream;
}
}

- 39,912
- 17
- 102
- 155

- 109
- 1
- 2
-
Thanks a lot, the perfect example that i was looking for................, but under wrong Topic this should have been here ==> [How to set an imageView's image from a string?](http://stackoverflow.com/questions/5254100/how-to-set-an-imageviews-image-from-a-string) – VenomVendor Jan 14 '12 at 17:52
Hi I have the most easiest code try this
public class ImageFromUrlExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(String url)
{
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
main.xml
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/ImageView01"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
try this

- 377
- 3
- 10
- 19
I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
Lots of good info in here...I recently found a class called SmartImageView that seems to be working really well so far. Very easy to incorporate and use.
http://loopj.com/android-smart-image-view/
https://github.com/loopj/android-smart-image-view
UPDATE: I ended up writing a blog post about this, so check it out for help on using SmartImageView.
2ND UPDATE: I now always use Picasso for this (see above) and highly recommend it. :)

- 3,147
- 11
- 62
- 104
This is a late reply, as suggested above AsyncTask
will will and after googling a bit i found one more way for this problem.
Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
imageView.setImageDrawable(drawable);
Here is the complete function:
public void loadMapPreview () {
//start a background thread for networking
new Thread(new Runnable() {
public void run(){
try {
//download the drawable
final Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
//edit the view in the UI thread
imageView.post(new Runnable() {
public void run() {
imageView.setImageDrawable(drawable);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Don't forget to add the following permissions in your AndroidManifest.xml
to access the internet.
<uses-permission android:name="android.permission.INTERNET" />
I tried this myself and i have not face any issue yet.

- 4,834
- 3
- 44
- 62
-
This is actually very nice for minimalism! Just keep in mind that it is required to run in an extra `Thread` because the UI thread does not allow for network operations. – creativecreatorormaybenot Mar 08 '18 at 13:02
-
Received an error - Attempt to invoke virtual method 'boolean android.widget.ImageView.post(java.lang.Runnable)' on a null object reference – meekash55 Apr 21 '21 at 12:15
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside

- 9,996
- 4
- 23
- 15
This will help you...
Define imageview and load image into it .....
Imageview i = (ImageView) vv.findViewById(R.id.img_country);
i.setImageBitmap(DownloadFullFromUrl(url));
Then Define this method :
public Bitmap DownloadFullFromUrl(String imageFullURL) {
Bitmap bm = null;
try {
URL url = new URL(imageFullURL);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}

- 2,657
- 1
- 22
- 19
String img_url= //url of the image
URL url=new URL(img_url);
Bitmap bmp;
bmp=BitmapFactory.decodeStream(url.openConnection().getInputStream());
ImageView iv=(ImageView)findviewById(R.id.imageview);
iv.setImageBitmap(bmp);

- 328
- 3
- 11
Version with exception handling and async task:
AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() {
public Bitmap mIcon_val;
public IOException error;
@Override
protected Boolean doInBackground(URL... params) {
try {
mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
} catch (IOException e) {
this.error = e;
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (success) {
image.setImageBitmap(mIcon_val);
} else {
image.setImageBitmap(defaultImage);
}
}
};
try {
URL url = new URL(url);
asyncTask.execute(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}

- 3,599
- 7
- 46
- 70
A simple and clean way to do this is to use the open source library Prime.

- 8,131
- 4
- 31
- 50
This code is tested, it is completely working.
URL req = new URL(
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"
);
Bitmap mIcon_val = BitmapFactory.decodeStream(req.openConnection()
.getInputStream());

- 23,698
- 16
- 85
- 87

- 31
- 1
Android Query can handle that for you and much more (like cache and loading progress).
Take a look at here.
I think is the best approach.

- 1,643
- 3
- 23
- 30

- 3,059
- 1
- 24
- 36
Working for imageView in any container , like listview grid view , normal layout
private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > {
ImageView ivPreview = null;
@Override
protected Bitmap doInBackground( Object... params ) {
this.ivPreview = (ImageView) params[0];
String url = (String) params[1];
System.out.println(url);
return loadBitmap( url );
}
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
ivPreview.setImageBitmap( result );
}
}
public Bitmap loadBitmap( String url ) {
URL newurl = null;
Bitmap bitmap = null;
try {
newurl = new URL( url );
bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
} catch ( MalformedURLException e ) {
e.printStackTrace( );
} catch ( IOException e ) {
e.printStackTrace( );
}
return bitmap;
}
/** Usage **/
new LoadImagefromUrl( ).execute( imageView, url );

- 6,056
- 1
- 32
- 30
Try this way,hope this will help you to solve your problem.
Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.
- Download "AndroidQuery" library from here
- Copy/Paste this jar to project lib folder and add this library to project build-path
- Now I show demo to how to use it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageFromUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="@+id/pbrLoadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private AQuery aQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aQuery = new AQuery(this);
aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
}
}
Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.

- 8,954
- 10
- 58
- 80

- 24,720
- 5
- 57
- 67
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}

- 2,180
- 2
- 24
- 53