每当我从Sqlite加载我的图片时,活动甚至无法启动,我的设备就会停止响应,即使在等待一段时间后屏幕上也看不到任何内容。
第二个问题是每当我从代码中删除bm.recycle()或b.recycle()时,它都会出现一个错误,说出OutOfMemory异常。那么我应该保留他们吗?如果不是我应该怎么做才能删除OutOfMemory异常?
这是我的代码:
public class ApplyLeave extends Activity {
ArrayList<String> name=new ArrayList<>();
ArrayList<String> description=new ArrayList<>();
ArrayList<Float> price=new ArrayList<>();
ArrayList<Bitmap> front=new ArrayList<>();
GridView g;
byte[] f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar=getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF989898")));
setContentView(R.layout.activity_apply_leave);
DbHelper help=new DbHelper(this);
Cursor cr=help.displayProducts();
cr.moveToFirst();
do{
name.add(cr.getString(cr.getColumnIndex("Name")));
description.add(cr.getString(cr.getColumnIndex("Description")));
price.add(cr.getFloat(cr.getColumnIndex("Price")));
if(cr.getBlob(cr.getColumnIndex("FrontSide"))!=null) {
f = cr.getBlob(cr.getColumnIndex("FrontSide"));
}
else if(cr.getBlob(cr.getColumnIndex("LeftSide"))!=null)
{
f = cr.getBlob(cr.getColumnIndex("LeftSide"));
}
else if(cr.getBlob(cr.getColumnIndex("RightSide"))!=null)
{
f = cr.getBlob(cr.getColumnIndex("RightSide"));
}
BitmapFactory.Options options=new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.inPurgeable = true; // inPurgeable is used to free up memory while required
options.inSampleSize=2;
Bitmap bm=BitmapFactory.decodeByteArray(f,0,f.length,options);
Bitmap b=Bitmap.createScaledBitmap(bm,50,50,true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, out);
front.add(b);
bm.recycle();
b.recycle();
}while(cr.moveToFirst());
g = (GridView)findViewById(R.id.g);
g.setAdapter(new ImageAdapter(this));
}
我的ImageAdapter类
public class ImageAdapter extends BaseAdapter{
Context c;
public ImageAdapter(Context context) {
c=context;
}
@Override
public int getCount() {
DbHelper help=new DbHelper(getApplication());
Cursor cr=help.displayProducts();
return cr.getCount();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
if ( convertView == null )
{
LayoutInflater inflater=getLayoutInflater();
view=inflater.inflate(R.layout.gridview,null);
TextView n= (TextView)findViewById(R.id.Name);
TextView p=(TextView)findViewById(R.id.Price);
p.setText(price.get(position).toString());
n.setText(name.get(position));
ImageView image=(ImageView)findViewById(R.id.RightSide);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setImageBitmap(front.get(position));
}
return view;
}