Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 422
Terance Wijesuriya Avatar asked May 15 '17 04:05

Terance Wijesuriya


People also ask

Which attribute is used to set an image in ImageView?

2. src: src is an attribute used to set a source file or you can say image in your imageview to make your layout attractive.

How do you insert a picture into Drawables?

To import image resources into your project, do the following: Drag and drop your images directly onto the Resource Manager window in Android Studio. Alternatively, you can click the plus icon (+), choose Import Drawables, as shown in figure 3, and then select the files and folders that you want to import.


2 Answers

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'

like image 113
Mohammad Zarei Avatar answered Nov 11 '22 20:11

Mohammad Zarei


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;

    }
}
like image 3
Ratilal Chopda Avatar answered Nov 11 '22 21:11

Ratilal Chopda