I saw this question: android, how to upload a 1mb image file and install it in ImageView
It does not solve my problem as it only shows how to display a bitmap after which you already have.
I am trying to download an image from a URL so that it displays using ImageView on an Android device. I am not sure how to do this.
I looked a bit on the Internet, this is the code that I still have:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);
URL url;
InputStream in;
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());
}
}
source
share