Let me describe my current situation:
When somebody uses very large Web images in their new items (that are used in Recycler), this code produces OOM:
public static Bitmap decodeSampledBitmap(String previewUrl, int reqWidth, int reqHeight) throws Exception {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // Decode with inJustDecodeBounds to check dimensions
URL url = new URL(previewUrl);
BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false; // Decode bitmap with appropriate inSampleSize set
return BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
}
I need the result from decodeSampledBitmap() method to compress & save for later use:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
And OOM error:
java.lang.OutOfMemoryError: Failed to allocate a 16396 byte allocation with 9344 free bytes and 9KB until OOM at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:645) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:622) at com.vsmapp.mainscreen.utils.PreviewImageHandler.decodeSampledBitmap(PreviewImageHandler.java:536)
I used the approach from Android Docs, but still OOM occurs: https://developer.android.com/topic/performance/graphics/load-bitmap#load-bitmap
Maybe I misunderstood something and this is not the best way how to load images:
URL url = new URL(previewUrl);
BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
What do you think, guys? Thanks in advance!