Is it a good practice to catch OutOfMemoryError even you have tried some ways to reduce memory usage? Or should we just not catching the exception? Which one is better practice?
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(file, options);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Thanks
You'd want to catch it if you want to display either a smaller image / different image / show a custom error message to the user. Your image access wrapper can catch these errors and return some custom error codes defined within your code; your activity that uses this code can decide what to do with the error code - warn user, force him to exit with a better error message than the one the android system would provide, etc.
Btw, you are not using the options variable in your sample code.
Though it might not be a good idea to catch OutOfMemoryError using try-catch. But, sometimes you have no choice, because all of us hate app crashes. So, what you can do is
How I did is:
And then on onCreate of Activity you can resume(something like this):
This approach saved my app. Hope it helps you too!!
I did something like this: I catch the error only for try to scale down the image until it works. Eventually it can not work at all; then returns null; otherwise, in success, returns the bitmap.
Outside I decide what to do with the bitmap whether it's null or not.
For example, with an image of 3264x2448, the loop iterates 2 times on my phone, and then it works.
Its good practice to catch it once and give
decodeFile
another chance. Catch it and callSystem.gc()
and try decoding again. There is a high probability that it will work after callingSystem.gc()
.