I have seen this question: android how to download an 1mb image file and set to ImageView
It does not solve my problem as it only shows how to display the bitmap after you already have it.
I am trying to download an image from a URL to have it be displayed with an ImageView on an Android device. I am not sure how to do this.
I've looked around a bit on the internet, this is the code I have so far:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set local image
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);
//Prepare to download image
URL url;
InputStream in;
//BufferedInputStream buf;
try {
url = new URL("http://i.imgur.com/CQzlM.jpg");
in = url.openStream();
out = new BufferedOutputStream(new FileOutputStream("testImage.jpg"));
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.close();
in.close();
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
The code would probably work, alltough you are downloading your image on your main thread. This means that when it takes more than 5 seconds to download, you will be presented with the famous ANR dialog, and your app will crash...
You should download your image in a background thread, and post the result back to your main thread. Back in the main thread, you can update your imageview with the downloaded image.
Here's an example:
Don't forget to add the permission.INTERNET to your manifest, if not, you will get an error...