Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Drawable.createFromStream allocated too much memory

I'm creating a Drawable from an http stream by doing the following.

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);

    HttpResponse response = client.execute(get);

    InputStream is = response.getEntity().getContent();

    Drawable drawable = Drawable.createFromStream(is, "offers task");

    return drawable;

My problem is that the Drawable.createFromStream is allocating a lot more memory than it should. The image I'm trying to download is 13k, but the createfromstream call is allocating a 16mb buffer causing an out of memory error.

E/AndroidRuntime( 8038): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=9066KB, Allocated=7325KB, Bitmap Size=16647KB)

Has anyone else run into this problem?

like image 320
Brian Griffey Avatar asked Apr 13 '11 18:04

Brian Griffey


1 Answers

the common practice of loading external images on android is to down sampling the image according to the size of the hosting ImageView.

steps: 1, download the original image.

2, use BitmapFactory.decodeFile(filePath, options) method to get the width and height of the image.

BitmapFactory.Options opt = new BitmapFactory.Options();
BitmapFactory.decodeFile(filePath, opt);
int width = opt.outWidth;
int height = opt.outHeight;

3, do your math, workout a sampleSize, and decode file:

opt = new BitmapFactory.Options();
opt.inSampleSize = theSampleSizeYouWant;
img = BitmapFactory.decodeFile(filePath, opt)

programming for android is like hell. android team seems not understanding what java is really about. the codes smell like MS C, in which you need to firstly pass a struct to get it's size, do the memory allocation yourself, pass it again and get the result. there are practically thousands of little traps you have to pay extra attentions to display an image from net. ( don't forget to use recyle() method to clear the memory after an image is no longer needed. android gc sucks)

like image 60
wangii Avatar answered Nov 16 '22 01:11

wangii