Android Recycler View Adapters, Viewpagers, Databases, Bitmaps And Out Of Memory Errors
Solution 1:
Apparently the huge number of images causes your app to crash with OutOfMemoryError
, and unfortunately you can do nothing if your app got this error, it will forced to be closed.
So, all you can do is to avoid the OutOfMemoryError
, and this can be done by a lot of ways:
1. assign a largeHeap
for your application:
you can do that by adding android:largeHeap="true"
to the <application>
tag inside your manifest.xml file.
2. override the onLowMemory method of your activity, which will enable you to take an action if the system feels like the memory is very low at some point:
@OverridepublicvoidonLowMemory() {
// you can here remove the Bitmaps or stopping the process of generating images or do whatever you want to survive being trapped into 'OutOfMemoryError'.
};
3. you can use any of the Image Libraries to changing the settings of your retrieved images, like reducing its resolution, reducing its size, and even reducing its color set, and the most common ones that are being used in this manner will be Universal-Image-Loader and Picasso, for example in Universal-Image-Loader you can use it in any process of downloading and displaying your Bitmap:
In your case, you have the Bitmap already loaded and all you want is to use an Image library to edit its options(here we will use UniversalImageLoader), in this case you can save the image as mentioned is this answer and after that load it from the memory with the options you gave to it:
// Saving image to diskStringfilename="some_name.jpg";
Filesd= Environment.getExternalStorageDirectory();
Filedest=newFile(sd, filename);
Bitmapbitmap= (Bitmap)data.getExtras().get("data");
try {
FileOutputStreamout=newFileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// this is an example of the used options
BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inSampleSize = 2;
options.inJustDecodeBounds = true;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
// create ImageLoader instanceImageLoaderloader= ImageLoader.getInstance();
loader.loadImageSync(dest.getAbsolutePath(), options);
Solution 2:
Try using Picasso Dependency : compile 'com.squareup.picasso:picasso:2.5.2
Picasso
.with(context)
.load(your_image)
.fit()
// call .centerInside() or .centerCrop() to avoid a stretched image.into(your_imageview);
Post a Comment for "Android Recycler View Adapters, Viewpagers, Databases, Bitmaps And Out Of Memory Errors"