I'm having problems with memory leaks. When I show an Activity every thing works. When I press back and try to reload the Activity I get an outOfMemoryException.
So from the docs I've read I can conclude that in this activity not all references are deleted and so the activity isn't recycled by the garbage collector (because Activitys with active references arent collected by the gc).
For instance could the code below cause a memory leak (Suppose there is a small amount of memory available)? Because I initialise the gestureDetector but I never uninitialise it:
public class FotoGallery extends Activity {
private GestureDetector gestureDetector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(new MyGestureDetector());
}
}
edit: I already have this problem when I set an image in an imageView.
public class FotoGallery extends Activity {
private GestureDetector gestureDetector;
private String path = "/mnt/sdcard/DCIM/img001.jpg";
private Bitmap currentBitmap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(new MyGestureDetector());
setImage(path);
}
private static final int SWIPE_MIN_DISTANCE = 30;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//rightFling detected
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//leftFling detected
}
} catch (Exception e) {
// nothing
}
return false;
}
}
private void setImage(String path) {
if (currentBitmap != null) {
currentBitmap.recycle();
}
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
currentBitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(currentBitmap);
}
}
Now my final question is how can you uninitialise all the variables at the right time? Do you specifically need to listen for when a user pr
esses back and then put all variables to null?