Loading Bitmap to ImageView from URL in android

2019-07-20 12:07发布

I am using following method to retrieve a bitmap from the url and pass it on to the imageview , but the imageview is not being updated.

 public static Bitmap LoadImageFromWebOperations(String url) {
    Bitmap bitmap;
    try {
        InputStream is = new URL(url).openStream();
       bitmap = BitmapFactory.decodeStream(is);
        return bitmap;
    } catch (Exception e) {
         return null;
    }

call -

  mov1_poster.setImageBitmap(VPmovies.LoadImageFromWebOperations(mov_details[0][7]));
//doesn't work

  Toast.makeText(this,"url is \n"+mov_details[0][7],Toast.LENGTH_LONG).show();
   // shows the url of the image successfully (just to check the url is not null)

Is there anything i am doing wrong ? Please help.

2条回答
看我几分像从前
2楼-- · 2019-07-20 12:50

Use the picasso library when working with images, it works wonders and it's easy!

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
查看更多
别忘想泡老子
3楼-- · 2019-07-20 12:59
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView imageView;
    private Bitmap image;

    public DownloadImageTask(ImageView imageView) {
        this.imageView = imageView;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            image = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            image = null;
        }
        return image;
    }

    @SuppressLint("NewApi")
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            imageView.setImageBitmap(result);
        }
    }
}

Now call in your code:

 new DownloadImageTask(YOUR_IMAGE_VIEW).execute("YOUR_URL");
查看更多
登录 后发表回答