I am trying to create an ImageSwitcher to browse the camera images on my DCIM. As I flip through the images, I get an OutOfMemory error. This makes perfect sense if memory is being allocated for each rather large image viewed. I have researched other similar issues, but I cannot figure out how to free up the memory of the old image when I switch to a new one.
public class MainActivity extends ActionBarActivity {
private ImageView imageView;
private ImageSwitcher imageSwitcher;
private String imageDir;
private File imageFile;
private String[] imageNames;
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
imageDir = getString(R.string.image_dir);
imageFile = new File(imageDir);
imageNames = imageFile.list();
i = imageNames.length - 1;
imageSwitcher.setFactory(new ViewFactory() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View makeView() {
// I tried testing for null here but that doesn't work
imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new
ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return imageView;
}
});
}
public void previous(View view) {
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(out);
imageSwitcher.setOutAnimation(in);
Uri imageUri = Uri.parse(imageDir+"/"+imageNames[i]);
imageSwitcher.setImageURI(imageUri);
decrementImage();
}
public void decrementImage() {
if (i == 0) {
i = imageNames.length - 1;
} else {
i--;
}
}
}
SOLUTION:
public void previous(View view) {
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(out);
imageSwitcher.setOutAnimation(in);
Uri imageUri = Uri.parse(imageDir+"/"+imageNames[i]);
imageSwitcher.setImageURI(null); // THIS FIXED THE OOM ERROR
imageSwitcher.setImageURI(imageUri);
decrementImage();
}