Tôi đã thấy câu hỏi này: android how to download an 1mb image file and set to ImageView
Nó không giải quyết vấn đề của tôi vì nó chỉ cho thấy làm thế nào để hiển thị bitmap sau bạn đã có nó.Tải hình ảnh cho ImageView trên Android
Tôi đang cố gắng tải xuống hình ảnh từ URL để hiển thị hình ảnh bằng ImageView trên thiết bị Android. Tôi không chắc chắn làm thế nào để làm điều này.
Tôi đã nhìn xung quanh một chút trên internet, đây là đoạn code tôi có cho đến nay:
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());
}
}
Nếu bạn tìm thấy một câu trả lời, bạn nên chấp nhận nó. Bằng cách đó, những người dùng khác biết rằng nó hoạt động. Chúc may mắn! – Entreco