So I'm loading images into Android Gallery from SD card. I hit menu and then select and it's inserted 开发者_运维百科into Gallery via code below. Problem is after about 5 or 6 images I get a out of memory error 01-04 18:10:35.246: ERROR/AndroidRuntime(10220): java.lang.OutOfMemoryError: bitmap size exceeds VM budget Any ideas on what I can do to resolve this?
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
mGalleryItemBackground = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(120, 120));
return i;
}
private Context mContext;
}
What is the width and height in pixels of the images you are inserting into the Gallery? If they are very large, perhaps 500x500 or larger then I'd suggest resizing them to something smaller and closer to your intended size of 120x120 before adding them to the Gallery.
You can scale them down using the method Bitmap.createScaledBitmap.
EDIT: Note that this is different from having the ImageView do the scaling. The ImageView will scale the bitmap as it is displayed but keeps the original bitmap in heap memory. If you use createScaledBitmap
and throw the original bitmap away then you'll be saving a lot of heap.
Try to avoid usage of
private Context mContext;
It's very bad practice to store Context/Activity as private members of classes. Context/Activity recommended to use only through parameters. Typical result of storing Context is a memory leaks, which I believe demonstrates your code. More you can read here.
精彩评论