setImageURI / setimagebitmap to fetch image from n

2019-05-23 06:52发布

I want to fetch image from net from some URL and show it in my ImageView. following is the code i am using :-

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

but i can not get the image

2条回答
2楼-- · 2019-05-23 07:14

I think better you can use below code, which works very well for me.

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);
查看更多
老娘就宠你
3楼-- · 2019-05-23 07:34

I think the error is in

URL aURL = new URL("stringURL");

should be without quotes

URL aURL = new URL(stringURL);

if stringURL is valid url it will work...

hope it helps../

查看更多
登录 后发表回答