Suresh Maidaragi
Suresh Maidaragi

Reputation: 2308

How to resolve java.lang.OutOfMemoryError exception when converting image url to bitmap in android?

This is the method i wrote to get image from url to bitmap, and i have made to run whenever i scroll down the main view using Handler

public void setimage(final ImageView imageview, final String urll,final int postion)
{

new Thread(new Runnable() 
 {

    @Override
    public void run() 
    {
        URL url = null;
        try {
            url = new URL(urll);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            final Bitmap myBitmap = BitmapFactory.decodeStream(input);

            handler.post(new Runnable() 
            {
                @Override
                public void run() {

                    imageview.setImageBitmap(Bitmap.createScaledBitmap(myBitmap, 160, 140, true));
                }
            });

            web.get(postion).setImage(myBitmap);

        }
        catch (IOException e) 
        {
            e.printStackTrace();

        }

    }

}).start();

}

This is the exception i am getting in Custom adapter whenever i scroll down to view more images in logcat

java.lang.OutOfMemoryError android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

Please let me know where i am doing wrong

Upvotes: 1

Views: 493

Answers (4)

Gaskoin
Gaskoin

Reputation: 2485

Both answers are really not too good. Large heap can mean anything. On some devices it will be ok, on some it won't. Android does not provide any information about how big this heap will be. If your bitmap is really big, you should download it not to the ram memory, but to the flash (some file). And than immediately read it scaled down. In this method you also has a cache implementation for free :)

Please check this article http://developer.android.com/training/displaying-bitmaps/index.html

Upvotes: 1

alfdev
alfdev

Reputation: 1049

You could use the decodeStream's overload that accept, in the third parameter, a BitmapOptions to scale down size and image's quality.

Have a look at this

Hope this can help you.

Upvotes: 1

Maveňツ
Maveňツ

Reputation: 1

You can request to use more by using

android:largeHeap="true"

in the manifest.

Reference: How to solve java.lang.OutOfMemoryError trouble in Android

Upvotes: 2

Hardik
Hardik

Reputation: 66

when you set bitmap before put this line

System.gc();

Upvotes: -1

Related Questions