Skip to content Skip to sidebar Skip to footer

BitmapFactory Returning Null Bitmap

I am trying to get the Bitmap from a URL from the StaticConfig.getMyUser().getAvatar(). The url is as follows 'https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAG

Solution 1:

As suggested by others, the ideal way would be to use Picasso or Glide.

Because it handles many things, from caching to memory optimisation for you. for eg. with Glide you will just have to write

Glide.with(context)
     .load("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg")
     .into(imgview);

Or If you want to write manually, you can use below method. imageview is instance of initialized Imageview.

public void setBitmapFromNetwork(){

Runnable runnable = new Runnable() {
    Bitmap bitmap = null;

    @Override
    public void run() {
        try {
            bitmap = getBitmapFromLink();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageview.post(new Runnable() {
            @Override
            public void run() {
                imageview.setImageBitmap(bitmap);
        }});
    }};
    new Thread(runnable).start();
}


public Bitmap getBitmapFromLink() throws IOException{
    HttpURLConnection conn =(HttpURLConnection) new URL("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg").openConnection());
    conn.setDoInput(true);
    InputStream ism = conn.getInputStream();
    Bitmap bitmap = BitmapFactory.decodeStream(ism);
    if (ism != null) {
        ism .close();
    }
    return bitmap;
}

And please make sure you have given Internet permission in manifest.


Solution 2:


Solution 3:

Just in case you want to use kotlin version.

class SetBitmapFromNetwork(img: ImageView?): AsyncTask<Void, Void, Bitmap>() {

    var img:ImageView? = img

    override fun doInBackground(vararg p0: Void?): Bitmap {

        val conn: HttpURLConnection = (URL("https://lh6.googleusercontent.com/-0feEeEohl8I/AAAAAAAAAAI/AAAAAAAAAGA/htLteFBdk5M/s96-c/photo.jpg").openConnection()) as HttpURLConnection

        conn.doInput = true

        val ism: InputStream = conn.inputStream

        return BitmapFactory.decodeStream(ism)


    }

    override fun onPostExecute(result: Bitmap?) {
        super.onPostExecute(result)
        img?.setImageBitmap(result)
    }
}

Just call as,

SetBitmapFromNetwork(img).execute()

Post a Comment for "BitmapFactory Returning Null Bitmap"