我想从互联网上获取照片,所以我使用setImageURI,但似乎无法完成,但如果我在同一个函数下使用setImageResource(R.drawable。),它的工作原理..如何修复setImageURI的错误?
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
//this is working
int p = R.drawable.fb;
i.setImageResource(p);
//this is not working.
i.setImageURI(Uri.parse("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));
return i;
}
答案 0 :(得分:1)
想从互联网上获取照片,所以我使用setImageURI,但似乎 不能完成,但如果我使用setImageResource(R.drawable。)
最重要的事情
setImageResource是同步的,因此它将正确执行,但是来自URL的setImageURI是异步操作,它必须在与UI线程不同的线程中执行
以下代码段会帮助您。
new Thread() {
public void run() {
try {
url = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = BitmapFactory.decodeStream(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
i.setImageBitmap(image);
}
});
}
}.start();
如果太不行,那么你还有其他三个选择
<强>选项1 强>
URL myUrl = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
InputStream inputStream = (InputStream)myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
i.setImageDrawable(drawable);
<强>选项2 强>
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
<强>选项3 强>
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;
}
i.setImageBitmap(loadBitmap("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));
答案 1 :(得分:0)
该图片网址对我不起作用。
我建议你去另一条路线从互联网上下载图像。如果您从setImageURI
拨打getView
,它将在UI线程上运行,这将导致您的应用冻结,直到从网络返回图像。此外,图像不会被缓存,因此您可能会一遍又一遍地下载相同的图像。
查看这个适用于Android的ImageLoader库,可以简化下载图片。它处理后台下载,它可以同时处理多个请求,并为您缓存图像。