Android : How to set an image to an imageview from a url programatically

谁都会走 提交于 2019-11-30 22:18:18

The easiest way to do it is by using something like Picasso or Glide:

Picasso.with(getContext()).load(imgUrl).fit().into(contentImageView);

you can add picasso library in your gradle: compile 'com.squareup.picasso:picasso:2.5.2'

Please Try this function to get bitmap

public Bitmap getBitmapfromUrl(String imageUrl)
{
    try
    {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

Use Glide or picasa library for efficient performance

Dependices

compile 'com.github.bumptech.glide:glide:3.7.0'

Sample Code

  Glide.with(this)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(imageview);

References: Glide official docs https://github.com/bumptech/glide

If you want to do it without any libraries:

  1. If you have bitmap image in memory

    setImageBitmap(Bitmap bm) // Sets a Bitmap as the content of this ImageView.

  2. If you have image in drawable folder

    setImageResource(int resId) // Sets a drawable as the content of this ImageView.

Reference: https://developer.android.com/reference/android/widget/ImageView.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!