OutOfMemoryException
在 Android 上,这是一个真正的痛苦。
目前我有一个画廊小部件,我在其中设置了 30 个 256x256 像素的图像,并使用 BaseAdapter 显示它们。
在某些时候,假设每秒钟尝试一次,当我想将ArrayList<Bitmap>
列表作为数据加载到图库时,应用程序就会崩溃。
我知道在内存中保留 30 个位图是愚蠢的,但有什么替代方法。我在资源中有它们,我需要它们在画廊中展示。
更新(适配器):
public class MyGalleryAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<MyDataObject> data = new ArrayList<MyDataObject>();
public GalleryItemsAdapter(Context context) {
mContext = context;
}
public int getCount() {
return data.size();
}
public DataHolder getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.single_item, null);
ImageView imgView = (ImageView) convertView.findViewById(R.id.single_item_image_view);
imgView.setImageBitmap(data.get(position).bitmap);
return convertView;
}
public void setData(ArrayList<MyDataObject> data) {
this.data = data;
}
}
private class MyDataObject {
public String title;
public Bitmap image;
}
}
更新(错误):
I/dalvikvm( 9073): "main" prio=5 tid=1 RUNNABLE
I/dalvikvm( 9073): | group="main" sCount=0 dsCount=0 obj=0x40a3c460 self=0x12828
I/dalvikvm( 9073): | sysTid=9073 nice=0 sched=0/0 cgrp=default handle=1074185352
I/dalvikvm( 9073): | schedstat=( 0 0 0 ) utm=437 stm=30 core=1
I/dalvikvm( 9073): at android.graphics.Bitmap.nativeCreate(Native Method)
I/dalvikvm( 9073): at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
I/dalvikvm( 9073): at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
I/dalvikvm( 9073): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
I/dalvikvm( 9073): at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
I/dalvikvm( 9073): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
I/dalvikvm( 9073): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
I/dalvikvm( 9073): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
I/dalvikvm( 9073): at android.content.res.Resources.loadDrawable(Resources.java:1937)
I/dalvikvm( 9073): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
I/dalvikvm( 9073): at android.view.View.<init>(View.java:2780)
I/dalvikvm( 9073): at android.view.View.<init>(View.java:2717)
I/dalvikvm( 9073): at android.view.ViewGroup.<init>(ViewGroup.java:379)
I/dalvikvm( 9073): at android.widget.RelativeLayout.<init>(RelativeLayout.java:174)
I/dalvikvm( 9073): at java.lang.reflect.Constructor.constructNative(Native Method)
I/dalvikvm( 9073): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)