how to clear the cached images in Android?

2019-04-17 05:02发布

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/

3条回答
【Aperson】
2楼-- · 2019-04-17 05:21

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.

查看更多
倾城 Initia
3楼-- · 2019-04-17 05:25

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-17 05:36

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.

查看更多
登录 后发表回答