android setImageURI / setimagebitmap从网络获取图像并在图像视图中显示

xdnvmnnf  于 2023-06-04  发布在  Android
关注(0)|答案(2)|浏览(257)

我想从一些网址从网络获取图像,并显示在我的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);

但我无法得到图像

wsewodh2

wsewodh21#

我认为错误在于

URL aURL = new URL("stringURL");

应该不带引号

URL aURL = new URL(stringURL);

如果stringURL是有效的URL,它将工作...
希望对你有帮助…

ia2d9nvy

ia2d9nvy2#

我认为你可以更好地使用下面的代码,这对我来说非常好。

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);

相关问题