How to recycle Bitmaps in gridview adapter? - android

I have a Grid View in my android app.I am loading images to the Grid view from server.I am using lazy loading. I have to recycle all bitmaps created here.How to do Bitmap.recycle() in Adapter or Grid view. I am getting out of memory, please help me.

You will need to show some code (your adapter at a minimum). If you're getting out of memory errors, you probably are not implementing view recycling correctly, or otherwise have a memory leak. Its also possible that you're simply loading too many large bitmaps at once, but if you can load the view at all, its much more likely you have a memory leak.
No one is going to be able to track down a memory leak without looking at some code. Bitmap.recycle() is not a solution, the garbage collector will work well enough without it if the rest of your code is ok.
See: http://www.youtube.com/watch?v=_CruQY55HOk for a great talk on managing memory in android and finding memory leaks.
Also try: http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html for an example of how to download or otherwise correctly asynchronously load images into a list like view.
Edit: also check out an image loading library I wrote, so you don't need to worry about any of this: https://github.com/bumptech/glide

Check out the Displaying Bitmaps Efficiently Android Training class. It has a lesson, Displaying Bitmaps in your UI, that covers displaying bitmaps in a GridView using a background thread and a memory and disk cache.

There is a really simple way that works very well:
First, you must create a custom ImageView like this:
public class ImageViewRecyclable extends ImageView
{
private Bitmap bitmap;
public ImageViewRecyclable(Context context)
{
super(context);
}
#Override
public void setImageBitmap(Bitmap bm)
{
super.setImageBitmap(bm);
if (bitmap != null) bitmap.recycle();
this.bitmap = bm;
}
}
Our ImageViewRecyclable keep a pointer to the bitmap and recycle the old one before setting the new one.
Second, you must check in the getView of the adapter to see if convertView is null or not. if it's not null cast to our custom ImageViewRecyclable and set the bitmap on it. this way the old bitmap is recycled before setting the new one.
This is the getView code of the adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageViewRecyclable imageView = (convertView == null) ? new ImageViewRecyclable(ActivityMain.this) : (ImageViewRecyclable) convertView;
byte[] bytes = ....
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bitmap);
return imageView;
}
I tested this code with 1000 100x100 images. The original ImageView failed after showing 50 image with memory error but this code works very well until the end of the grid.
This code works very great for small offline images, but online and large images need caching and other things. This may be useful but some changes must be applied.

Related

how to recyle the bitmap which runs multi-thread

the activity displays the bitmap which load from the internet ,when I slip the ImageView,another bitmap will occur.I set the bitmap to ImageView and after recycle it, sometimes,the error has occurs.
the code:
mImageView.setImageBitmap(loadedBitmap);
if(loadedBitmap!=null && !loadedBitmap.isRecycled()){
loadedBitmap.recycle();
loadedBitmap=null;
}
It runs multi-thread,I can not put the operation of Bitmpa recycle ahead of setImageBitmap.
how should I do?
Well basically you cannot recycle a bitmap that you're currently using in your ImageView.
If you want to swap the bitmap in your ImageView then I would do it like this:
I would keep a reference to the Bitmap (in for example mLoadedBitmap), and when you download another one you do something like this:
final Bitmap oldBitmap = mLoadedBitmap;
mLoadedBitmap = downloadedBitmap;
mImageView.setImageBitmap(mLoadedBitmap);
if(oldBitmap!=null && !oldBitmap.isRecycled()){
oldBitmap.recycle();
}
You can write a multi-threaded application but do all the UI updates from the main thread.

BitmapFun sample has a caching issue

I am using the Android BitmapFun sample code to manage bitmaps in my application. I have been experiencing garbled or duplicated images in a ViewPager. I have tracked this down to the following code in ImageCache.java:
/**
* Notify the removed entry that is no longer being cached
*/
#Override
protected void entryRemoved(boolean evicted, String key,
BitmapDrawable oldValue, BitmapDrawable newValue) {
if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
// The removed entry is a recycling drawable, so notify it
// that it has been removed from the memory cache
((RecyclingBitmapDrawable) oldValue).setIsCached(false);
} else {
// The removed entry is a standard BitmapDrawable
if (Utils.hasHoneycomb()) {
// We're running on Honeycomb or later, so add the bitmap
// to a SoftRefrence set for possible use with inBitmap later
mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
}
}
}
The bitmap is added to the reusable bitmap list when it is removed from the cache. In this case the bitmap is still in use by a ViewPager view. When a later view is created the bitmap (still in use) is reused and the bitmap appears in two positions in the ViewPager.
A bitmap that is removed from the LruCache isn't necessarily available for reuse. I have disabled the reuse of bitmaps in this code and am no longer having an issue. This problem doesn't occur with lower resolution images because the bitmaps aren't removed from the cache while in the range of the ViewPager's offscreen limit. I don't have an issue with 60 DPI images but see this issue frequently at 160 DPI. I think this would show up in the original BitmapFun sample with higher resolution images.
Anyone else experienced this problem or I am not understanding the issue properly?
Kevin
What I think the problem with the code is in the line
mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
That line adds a bitmap that was removed from LRU cache to a reusable bitmap set to be used for inBitmap re-use. It doesn't check whether it is still being used by an ImageView or not. If you try to re-use a bitmap that is still being used by an ImageView, the underlying bitmap will be replaced with another bitmap making it not valid anymore. My suggestion is to track whether a bitmap is still being used by an ImageView before adding it to the reusable bitmap set. I've created a sample github project for this issue. Tell me what you think with my solution.

Is it safe to call native function that locks pixels of Bitmap from non UI thread?

I'm implementing list that contains preview of different image filters (grayscale, sepia, etc.)
I want to move image processing out of UI thread, but I'm not sure is it safe. For example, when I'm calling AndroidBitmap_lockPixels for Bitmap of ImageView what will happen if UI thread will try to redraw ImageVIew?
EXAMPLE
public void someMethod(){
ImageView mImageView = /*initialization*/
final Bitmap bmp = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
new Thread(new Runnable(){
#Override
public void run(){
applyFilter(bmp);
}
}).start();
}
public native void applyFilter(Bitmap bmp);
I haven't tried this case yet; however, you're trying to modify the current being-used Bitmap on ImageView. I think when AndroidBitmap_lockPixels is called, some abnormal will happen, like crash on ImageView while trying to invalidate or something similar to Access Violation.
You can make a copy of the image, process it then apply the new Bitmap to ImageView; it's totally safe.
In that case, there's a chance that the Bitmap is directly referencing something in that ImageView. Otherwise, the Bitmap becomes just another set of 1s and 0s. You might be able to make a copy of the Bitmap and update the ImageView with the new image once you are done. Be careful about images on devices before Honeycomb (3.0) because they handle bitmaps weird, and you have to manage them almost like you would in a C++ program.
It shouldn't, but there's sometimes hidden things in Android, so watch out.
Update: there might be a way to modify the image without copying, but I'm basing this more off general graphics and not Android-specific

Android Bitmap Cache

I'm working on implementing a cache for a lot of bitmap tiles I have. What I've done so far:
Successfully implemented a LRU Cache system, but the tiles still load slowly when they must be loaded from the app's resources. The cache currently has about an 85% hit rate.
Whenever I must load the bitmap from resources, it is still slow like I said. With this in mind, I am now loading the Bitmaps from an Async task. Before this, everything would load without error, but it was fairly slow. Now, it's faster since it's not working on the main thread, but I inevitably run into an OOM error. Here's the code for my Async task:
public class loadBitmap extends AsyncTask<Void,Void,Void>
{
Bitmap bit;
#Override
protected Void doInBackground(Void... params)
{
Options opts = new Options();
bit = BitmapFactory.decodeResource(reso, drawable, opts);
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
drawLoadedBit(bit);
super.onPostExecute(result);
}
}
Any ideas on how I can implement this so I don't get the Out of Memory error? Since this is called in the draw method, I'm thinking that the multiple calls to it are causing it. Thanks for any advice.
Refer to this link
He gives a good tutorial on using regenative bitmaps. Further, to decouple the bitmap from the view [once the view is disposed], you can #Override View#onRemovedFromWindow() to recycle the bitmap. Going even further, if you still have this issue, you can create a BitmapPool in which you allocate your bitmaps. You can implement an algorithm go calculate the sizes of the bitmaps and release older bitmaps that would push you over an arbitrary memory amount (bitamp memory is about width*height*4 + object size which should be nominal)
When the Bitmap is loaded, keep it around in a class variable. Then next time a draw is requested, check to see if the class variable is non-null before loading it from resources again.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I developed an application that uses lots of images on Android.
The app runs once, fills the information on the screen (Layouts, Listviews, Textviews, ImageViews, etc) and user reads the information.
There is no animation, no special effects or anything that can fill the memory.
Sometimes the drawables can change. Some are android resources and some are files saved in a folder in the SDCARD.
Then the user quits (the onDestroy method is executed and app stays in memory by the VM ) and then at some point the user enters again.
Each time the user enters to the app, I can see the memory growing more and more until user gets the java.lang.OutOfMemoryError.
So what is the best/correct way to handle many images?
Should I put them in static methods so they are not loaded all the time?
Do I have to clean the layout or the images used in the layout in a special way?
One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frequently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory available for bitmaps.
Bitmaps on the previous activity layout are not properly de-allocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.
First, set the “id” attribute on the parent view of your XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/RootView"
>
...
Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a reference to the parent View and then do a System.gc().
#Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
This unbindDrawables() method explores the view tree recursively and:
Removes callbacks on all the background drawables
Removes children on every viewgroup
It sounds like you have a memory leak. The problem isn't handling many images, it's that your images aren't getting deallocated when your activity is destroyed.
It's difficult to say why this is without looking at your code. However, this article has some tips that might help:
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
In particular, using static variables is likely to make things worse, not better. You might need to add code that removes callbacks when your application redraws -- but again, there's not enough information here to say for sure.
To avoid this problem you can use native method Bitmap.recycle() before null-ing Bitmap object (or setting another value). Example:
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
}
And next you can change myBitmap w/o calling System.gc() like:
setMyBitmap(null);
setMyBitmap(anotherBitmap);
I've ran into this exact problem. The heap is pretty small so these images can get out of control rather quickly in regards to memory. One way is to give the garbage collector a hint to collect memory on a bitmap by calling its recycle method.
Also, the onDestroy method is not guaranteed to get called. You may want to move this logic/clean up into the onPause activity. Check out the Activity Lifecycle diagram/table on this page for more info.
This explanation might help:
http://code.google.com/p/android/issues/detail?id=8488#c80
"Fast Tips:
1) NEVER call System.gc() yourself. This has been propagated as a fix here, and it doesn't work. Do not do it. If you noticed in my explanation, before getting an OutOfMemoryError, the JVM already runs a garbage collection so there is no reason to do one again (its slowing your program down). Doing one at the end of your activity is just covering up the problem. It may causes the bitmap to be put on the finalizer queue faster, but there is no reason you couldn't have simply called recycle on each bitmap instead.
2) Always call recycle() on bitmaps you don't need anymore. At the very least, in the onDestroy of your activity go through and recycle all the bitmaps you were using. Also, if you want the bitmap instances to be collected from the dalvik heap faster, it doesn't hurt to clear any references to the bitmap.
3) Calling recycle() and then System.gc() still might not remove the bitmap from the Dalvik heap. DO NOT BE CONCERNED about this. recycle() did its job and freed the native memory, it will just take some time to go through the steps I outlined earlier to actually remove the bitmap from the Dalvik heap. This is NOT a big deal because the large chunk of native memory is already free!
4) Always assume there is a bug in the framework last. Dalvik is doing exactly what its supposed to do. It may not be what you expect or what you want, but its how it works. "
I had the exact same problem. After a few testing I found that this error is appearing for large image scaling. I reduced the image scaling and the problem disappeared.
P.S. At first I tried to reduce the image size without scaling the image down. That did not stop the error.
Following points really helped me a lot. There might be other points too, but these are very crucial:
Use application context(instead of activity.this) where ever possible.
Stop and release your threads in onPause() method of activity
Release your views / callbacks in onDestroy() method of activity
I suggest a convenient way to solve this problem.
Just assign the attribute "android:configChanges" value as followed in the Mainfest.xml for your errored activity.
like this:
<activity android:name=".main.MainActivity"
android:label="mainActivity"
android:configChanges="orientation|keyboardHidden|navigation">
</activity>
the first solution I gave out had really reduced the frequency of OOM error to a low level. But, it did not solve the problem totally. And then I will give out the 2nd solution:
As the OOM detailed, I have used too much runtime memory. So, I reduce the picture size in ~/res/drawable of my project. Such as an overqualified picture which has a resolution of 128X128, could be resized to 64x64 which would also be suitable for my application. And after I did so with a pile of pictures, the OOM error doesn't occur again.
I too am frustrated by the outofmemory bug. And yes, I too found that this error pops up a lot when scaling images. At first I tried creating image sizes for all densities, but I found this substantially increased the size of my app. So I'm now just using one image for all densities and scaling my images.
My application would throw an outofmemory error whenever the user went from one activity to another. Setting my drawables to null and calling System.gc() didn't work, neither did recycling my bitmapDrawables with getBitMap().recycle(). Android would continue to throw the outofmemory error with the first approach, and it would throw a canvas error message whenever it tried using a recycled bitmap with the second approach.
I took an even third approach. I set all views to null and the background to black. I do this cleanup in my onStop() method. This is the method that gets called as soon as the activity is no longer visible. If you do it in the onPause() method, users will see a black background. Not ideal. As for doing it in the onDestroy() method, there is no guarantee that it will get called.
To prevent a black screen from occurring if the user presses the back button on the device, I reload the activity in the onRestart() method by calling the startActivity(getIntent()) and then finish() methods.
Note: it's not really necessary to change the background to black.
The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).
Well I've tried everything I found on the internet and none of them worked. Calling System.gc() only drags down the speed of app. Recycling bitmaps in onDestroy didn't work for me too.
The only thing that works now is to have a static list of all the bitmap so that the bitmaps survive after a restart. And just use the saved bitmaps instead of creating new ones every time the activity if restarted.
In my case the code looks like this:
private static BitmapDrawable currentBGDrawable;
if (new File(uriString).exists()) {
if (!uriString.equals(currentBGUri)) {
freeBackground();
bg = BitmapFactory.decodeFile(uriString);
currentBGUri = uriString;
bgDrawable = new BitmapDrawable(bg);
currentBGDrawable = bgDrawable;
} else {
bgDrawable = currentBGDrawable;
}
}
I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.
ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));
FWIW, here's a lightweight bitmap-cache I coded and have used for a few months. It's not all-the-bells-and-whistles, so read the code before you use it.
/**
* Lightweight cache for Bitmap objects.
*
* There is no thread-safety built into this class.
*
* Note: you may wish to create bitmaps using the application-context, rather than the activity-context.
* I believe the activity-context has a reference to the Activity object.
* So for as long as the bitmap exists, it will have an indirect link to the activity,
* and prevent the garbaage collector from disposing the activity object, leading to memory leaks.
*/
public class BitmapCache {
private Hashtable<String,ArrayList<Bitmap>> hashtable = new Hashtable<String, ArrayList<Bitmap>>();
private StringBuilder sb = new StringBuilder();
public BitmapCache() {
}
/**
* A Bitmap with the given width and height will be returned.
* It is removed from the cache.
*
* An attempt is made to return the correct config, but for unusual configs (as at 30may13) this might not happen.
*
* Note that thread-safety is the caller's responsibility.
*/
public Bitmap get(int width, int height, Bitmap.Config config) {
String key = getKey(width, height, config);
ArrayList<Bitmap> list = getList(key);
int listSize = list.size();
if (listSize>0) {
return list.remove(listSize-1);
} else {
try {
return Bitmap.createBitmap(width, height, config);
} catch (RuntimeException e) {
// TODO: Test appendHockeyApp() works.
App.appendHockeyApp("BitmapCache has "+hashtable.size()+":"+listSize+" request "+width+"x"+height);
throw e ;
}
}
}
/**
* Puts a Bitmap object into the cache.
*
* Note that thread-safety is the caller's responsibility.
*/
public void put(Bitmap bitmap) {
if (bitmap==null) return ;
String key = getKey(bitmap);
ArrayList<Bitmap> list = getList(key);
list.add(bitmap);
}
private ArrayList<Bitmap> getList(String key) {
ArrayList<Bitmap> list = hashtable.get(key);
if (list==null) {
list = new ArrayList<Bitmap>();
hashtable.put(key, list);
}
return list;
}
private String getKey(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Config config = bitmap.getConfig();
return getKey(width, height, config);
}
private String getKey(int width, int height, Config config) {
sb.setLength(0);
sb.append(width);
sb.append("x");
sb.append(height);
sb.append(" ");
switch (config) {
case ALPHA_8:
sb.append("ALPHA_8");
break;
case ARGB_4444:
sb.append("ARGB_4444");
break;
case ARGB_8888:
sb.append("ARGB_8888");
break;
case RGB_565:
sb.append("RGB_565");
break;
default:
sb.append("unknown");
break;
}
return sb.toString();
}
}

Categories

Resources