MrTimotheos
MrTimotheos

Reputation: 937

Why is BitmapFactory.decodeStream returning null?

Basically I am parsing some JSON that has an image with it and trying to load it into a ImageView. However mBitmap is returning null. I have no idea why and further research has not helped..

Here is an example url I am working with:

http://b.thumbs.redditmedia.com/ivBAJzLMJEkEy9jgTy3z4n-mO7gIGt5mQFU1Al5kJ-I.jpg

Here is all relevant code:

 public static Bitmap LoadImageFromUrl(String url){
   try {
      mBitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
       return mBitmap;
    }catch (Exception e){
       Log.d(TAG,"Error getting image");
       return null;
   }
}

Here is where the method is called:

mListingModel.setmImageView(LoadImageFromUrl(data.getString(JSON_THUMBNAIL)));

Here is where I set the ImageView:

    if(mItem.getmImageView() != null) {
        holder.imageView.setImageBitmap(mItem.getmImageView());
    }

Note: I am calling the method in an AsyncTask so that is not the problem.

Upvotes: 3

Views: 3820

Answers (4)

mazend
mazend

Reputation: 464

I had the same problem.

I tried to find decode fail reason.. but I couldn't find. I just confirmed that InputStream and BufferedInputStream are not null.

After restarting my AVD.. the problem was resolved even though I didn't change any code.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317948

The javadoc for Bitmap.decodeStream() states that:

If the input stream is null, or cannot be used to decode a bitmap, the function returns null

You're passing it the results of URL.getContent(), which states in its javadoc:

By default this returns an InputStream, or null if the content type of the response is unknown.

So maybe you should check to see if getContent() returns null before passing it on to the decoder.

Upvotes: 2

Not Important
Not Important

Reputation: 804

i had in the past stupid problems like having my stream reached the end before i decoded it, so ensure to set it's position to 0 before decoding the stream

eg.

stream.Position = 0;
var bmp = BitmapFactory.DecodeStream(stream);

Upvotes: 1

ZakiMak
ZakiMak

Reputation: 2102

Can you check if this works for you:

InputStream in = new java.net.URL(downloadURL).openStream();
Bitmap avatarBmp = BitmapFactory.decodeStream(in);
in.close();

Also a reminder to add this in your Manifest

<uses-permission android:name="android.permission.INTERNET" />

Upvotes: 0

Related Questions