I have option to save Bitmap
to sdcard in my app.
I am doing saving in AsyncTask
method. here is what i do on background
public File saveImageToExternalStorage(Bitmap image, String name) {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, name.replaceAll("/", "").trim());
file.createNewFile();
fOut = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
return file;
} catch (Exception e) {
return null;
}
I am displaying some information about failing to save and etc for user if I get null from this method. I though this should be sufficient, yet I got reported OutOfMemory
crash by one user from this method. Stacktrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:527)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:301)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:326)
at android.provider.MediaStore$Images$Media.insertImage(MediaStore.java:796)
at com.stancedcars.wallpapers.FullSelected.saveImageToExternalStorage(FullSelected.java:223)
I would love to solve OutOfMemory
issue, but Bitmap
s are heavy in size, high resolution images, I wouldn't want to reduce quality. More importantly I would like to know why the app crashed even though it was in try catch ?