2

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.

1

2 Answers 2

7
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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , very helpful . Once i checked the log , found out NetworkOnMainThreadException was the reason , This exception is thrown when an application attempts to perform a networking operation on its main thread . And for this your answer was correct , running the operation inside a separate(background) thread .
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.