I’m developing an Android 3.1 tablet application and I have a Fragment (android.support.v4.app.Fragment) with two galleries.
I use this code as for gallery (I use the same adapter for both Galleries):
public class ImageGalleryAdapter extends BaseAdapter
{
private ArrayList<String> mImagesPath;
private Context mContext;
private ImageView.ScaleType mScaleType;
private int mWidth;
private int mHeight;
public ArrayList<String> getmImagesPath()
{
return mImagesPath;
}
public void setmImagesPath(ArrayList<String> mImagesPath)
{
this.mImagesPath = mImagesPath;
}
public void addImage(String imagePath)
{
mImagesPath.add(imagePath);
}
public ImageGalleryAdapter(Context context, ImageView.ScaleType scaleType, int width, int height)
{
mContext = context;
mWidth = width;
mHeight = height;
mScaleType = scaleType;
mImagesPath = new ArrayList<String>();
}
@Override
public int getCount()
{
return mImagesPath.size();
}
@Override
public Object getItem(int position)
{
return position;
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// Get a View to display image data
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
} else {
imageView = (ImageView) convertView;
}
File imageFile = new File(mImagesPath.get(position));
if(imageFile.exists())
{
BitmapFactory.Options options = new Options();
options.inSampleSize = 32;
imageView = new ImageView(this.mContext);
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
imageView.setImageBitmap(myBitmap);
imageView.setScaleType(mScaleType);
// Set the Width & Height of the individual images
imageView.setLayoutParams(new Gallery.LayoutParams(mWidth, mHeight));
}
return imageView;
}
}
Somtimes, at the line Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());, I get an Out Of Memory error
One gallery has one image and the other one has three images.
The Out Of Memory occurs when I go to the fragment, tap on back button and then I come back to the fragment again.
I think I need to call myBitmap.recycle() but where…
Try that in your else case when your convertview is not null:
About how many images and at which size are we talking? Have you tried to set the adapter null in your onStop()? This could remove all references and free memory, too.