how to clear the cached images in Android?

耗尽温柔 提交于 2019-12-22 01:22:13

问题


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/


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2929248/how-to-clear-the-cached-images-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!