I wrote yesterday about memoryleaks and out-of-memory.
see my post:
memory leak and out of memory
I have good tips on using a memory profiler, and I started using it, and I might have found something, but couldn't solve it. In DDMS, you can choose to track object allocation. I found something interesting by clicking on a sublistitem (which loads 9 images in a scrollview). ) Images should be selected 9 times - but I could see that it was selected 27 times. 9 times allocated due to the createScaledBitmap method of the Bitmap class, then 18 times due to a call to the BitmapFactory class. WHY???
I will post methods that scale bitmaps below. Can the code be written better? Is it logical that resources are allocated 27 times for 9 images? Am I calling BitmapFactory.decodeResource too many times, for example? But I could only recycle once.
the import and decodeSampledBitmapFromResource method below
Useful for answers !!!
public int calculateInSampleSize(BitmapFactory.Options options, int reqW, int reqH) { int imageHeight = options.outHeight; int imageWidth = options.outWidth; int inSampleSize = 1; if (imageHeight > reqH || imageWidth > reqW) { int heightRatio = Math.round((float) imageHeight / (float) reqH); int widthRatio = Math.round((float) imageWidth / (float) reqW); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; System.out.println("i if-satsen!"); System.out.println("height-ratio: " + heightRatio + "\nwidth-ratio: " + widthRatio); } System.out.println("samplesize: " + inSampleSize); inSampleSize = inSampleSize; return inSampleSize; } @SuppressLint("NewApi") public Bitmap[] decodeSampledBitmapFromResource(Resources res, int[] resId, int[] reqW, int[] reqH) { this.scaledBitmap = new Bitmap[resId.length]; BitmapFactory.Options options; for (int i = 0; i < resId.length; i++) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId[i], options); System.out.println("ursprunglig bild: h = " + options.outHeight + " w = " + options.outWidth); options.inSampleSize = calculateInSampleSize(options, reqW[i], reqH[i]); while (options.outHeight < reqH[i] || options.outWidth < reqW[i]) { options.inSampleSize--; System.out.println("räknar nu ner insampleseize\ninSamleSize =" + options.inSampleSize); } options.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeResource(res, resId[i], options); System.out.println("innan omskalning: h = " + options.outHeight + " w = " + options.outWidth); System.out.println("antalet bytes: " + bm.getByteCount()); System.out.println("native free size: " + Debug.getNativeHeapFreeSize() ); this.scaledBitmap[i] = Bitmap.createScaledBitmap(bm, reqW[i], reqH[i], true); bm.recycle(); } System.gc(); return this.scaledBitmap; }
source share