In my application I have photos, videos, etc.. In the case of images, I have done scaling, but sometimes I get an OutOfMemoryError
. How can I handle the error efficiently?
OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.
Check that the image size is smaller than the available memory before attempting to load it. So the most efficient way to handle OutOfMemoryException is to architecture your application in such a way that it never attempts to load lots of data into memory in order to avoid the exception.
There is a method in Activity which is called when the device is coming low of memory, but this can only be used to trigger cache files cleaning. This does not mean that your application process is coming out of memory.
You could also add a try catch block to catch Error or OutOfMemoryError, but this would be too late.
Handling large numbers of Bitmaps or large Bitmaps is really difficult in android applications. You'll find some tips on this subject in this article from Romain Guy.
You can also take care of loading bitmaps directly to the resolution you need by specifying a sample size in the BitmapFactory.options you provide to BitmapFactory.decode*() methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With