Android : How to set an image to an imageview from

2019-02-14 04:21发布

I have an image url coming from my rest API. Now I want to set it to an imageview when activity is loading. Below is how I get the bean from the rest api and then get the URL out of it.

Message message=new Message();
String imageUrl=message.getImageUrl();

I get Message object from my database and image url is include in that Message object.

Then I used Url object to get that image url.

URL url = null;
try {
     url = new URL(imageUrl);
     Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
     contentImageView.setImageBitmap(bmp);
} catch (Exception e) {
     e.printStackTrace();
}

I used above codes to load image to an imageview object which is contentImageView.

But still I cannot load this image to imageview, Nothing is getting loaded.

have any ideas?

4条回答
三岁会撩人
2楼-- · 2019-02-14 04:44

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

查看更多
forever°为你锁心
3楼-- · 2019-02-14 04:57

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;

    }
}
查看更多
smile是对你的礼貌
4楼-- · 2019-02-14 04:59

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'

查看更多
对你真心纯属浪费
5楼-- · 2019-02-14 05:00

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

查看更多
登录 后发表回答