2

我想从某个 URL 从网络中获取图像并将其显示在我的 ImageView 中。以下是我正在使用的代码:-

Bitmap bm = null;
    try {
         URL aURL = new URL("stringURL"); 
         URLConnection conn = aURL.openConnection();
         conn.connect(); 
         InputStream is = conn.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);
         bm = BitmapFactory.decodeStream(bis);
         bis.close();
         is.close(); 
    }catch (Exception e) {
        // TODO: handle exception
}
    iv.setImageBitmap(bm);

但我无法获得图像

4

2 回答 2

0

我认为错误在于

URL aURL = new URL("stringURL");

应该没有引号

URL aURL = new URL(stringURL);

如果 stringURL 是有效的 url,它将起作用......

希望能帮助到你../

于 2011-03-25T09:02:35.737 回答
0

我认为你可以使用下面的代码更好,这对我来说效果很好。

String stringURL = "Your url here";

InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;

try {
    URL url = new URL(stringURL);   
    URLConnection conn = url.openConnection();
    conn.connect();
    is = conn.getInputStream();
    bis = new BufferedInputStream(is);
    bmp = BitmapFactory.decodeStream(bis);

} catch (MalformedURLException e) {

} catch (IOException e) {

}catch (Exception e) {

} finally {
    try {
        if( is != null )
            is.close();
        if( bis != null )
            bis.close();
    } catch (IOException e) {

    }
}
iv.setImageBitmap(bmp);
于 2011-03-25T09:15:38.620 回答