开发者

how to clear the cached images in Android?

How to clear the cached image from memory programatically in Android?

I have a ListView with icons when 开发者_运维百科I scroll its reloads the image. So its produce the OutofMemoryError. I want clear the cache while gets this exception. how to do that? any help?

EDIT:

i am just using this code on my program to loadimage: http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/


Are you re-using the bitmap objects in the ListView?

Romain Guy talked about how important this is for memory and smooth performance in his Android talk on layouts and views at Google I/O last year.

Essentially, you should have a certain number of bitmap objects (he used 8) and every time you load the next image as you scroll, it should go into the object of the one that just disappeared.

You might think caching the images is faster, but it causes memory problems and garbage collecting issues which inevitably causes lag.


Yup... known "problem", let say this is the behaviour of the ListView.

How to fix it:

  1. Watch the first 15min of the video as suggested by @HXCaine, which explains the ViewHolder.

  2. If I'm not mistaken your example should set the default image when a bitmap is null! In the example you do not provide this to a view and so it gets cached. Shur this should be handled by the framework but it is not :(.

Example code:

public class DebtAdapter extends BaseAdapter {
...

    @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            ViewHolder holder;
            Bitmap bitmap;

            if(convertView == null)  
            {
                convertView = inflater.inflate(viewResourceId, null);

                holder = new ViewHolder();
                holder.photo = (ImageView) convertView.findViewById(R.id.photo);

                convertView.setTag(holder);
            }
            else 
            {
                holder = (ViewHolder) convertView.getTag();
            }
            bitmap = item.getContact().getPhoto();
            if(bitmap != null)
            {
                holder.photo.setImageBitmap(bitmap);
            }
            else
            {
                holder.photo.setImageBitmap(null);
            }
            return convertView;
        }
}

I hope it helps.


You can free up some memory by calling the recycle method if you're using Bitmap. However, I'm not really sure if this will solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜