Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle OutOfMemoryError

Tags:

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?

like image 879
Bytecode Avatar asked Dec 28 '10 09:12

Bytecode


People also ask

What is OutOfMemoryError in Java?

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.


2 Answers

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.

like image 127
Darin Dimitrov Avatar answered Sep 20 '22 18:09

Darin Dimitrov


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.

like image 34
Kevin Gaudin Avatar answered Sep 20 '22 18:09

Kevin Gaudin