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.

publicvoidsetBitmapFromNetwork(){

Runnablerunnable=newRunnable() {
    Bitmapbitmap=null;

    @Overridepublicvoidrun() {
        try {
            bitmap = getBitmapFromLink();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageview.post(newRunnable() {
            @Overridepublicvoidrun() {
                imageview.setImageBitmap(bitmap);
        }});
    }};
    newThread(runnable).start();
}


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

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

Solution 2:

At first you need to download image from that url. It's better to use a image loader like Glide

or Picasso

Solution 3:

Just in case you want to use kotlin version.

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

    var img:ImageView? = img

    overridefundoInBackground(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 = trueval ism: InputStream = conn.inputStream

        return BitmapFactory.decodeStream(ism)


    }

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

Just call as,

SetBitmapFromNetwork(img).execute()

Post a Comment for "Bitmapfactory Returning Null Bitmap"