简体   繁体   中英

Android: ImageView load from URL

Tried many ways in the internet but my imageView still display blank of the image. Wish to retrieve the image from url (download or refer it) but seems I missed out something. I have activated the INTERNET permission in manifest.

 icon.setImageResource(R.drawable.portrait_user);

        try {
            URL url = new URL("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/t1.0-1/c0.0.50.50/p50x50/1499583_10202305028778787_1063740680_n.jpg");
            InputStream content = (InputStream)url.getContent();
            Bitmap d = BitmapFactory.decodeStream(content);
            icon.setImageBitmap(d);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Doing network I/O on the main application thread like this will crash your app on Android 4.0+.

Most likely, you will be better served using a third-party library that can download the image for you in the background and update the ImageView when it is ready. Picasso and Universal Image Loader are two of the more popular libraries for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM