views:

186

answers:

2

I use GridView to display thumbnails from MediaStore. If I launch and close my application 2-3 times it crashes with out of memory error. System.gc() is called in onCreate of main activity. If comment call setImageURI then no errors. Maybe I need to explicitly clear memory somehow? Please, help.

   public View getView(int position, View convertView, ViewGroup parent){
           ImageView i;
           if (convertView == null) {
                   i = new ImageView(activity.getApplicationContext());
                   i.setLayoutParams(new GridView.LayoutParams(92, 92));
                   i.setScaleType(ImageView.ScaleType.CENTER_CROP);
           } else {
                   i = (ImageView) convertView;
           }
           Uri imageUri = thumbUri(position);
           i.setImageURI(imageUri);   //  <--- no error if this string is commented
           return i;
   }
A: 

It seems you are leaking memory elsewhere. Try to remove all callbacks from your ImageView with something like this:

@Override
protected void onDestroy(){
    super.onDestroy();

    int count = gridView.getCount();
    for (int i = 0; i < count; i++){

        final ImageView v = (ImageView) gridView.getChildAt(i);
        v.getDrawable().setCallback(null);
    }



}
Francesco
no luck. How to debug unreleased resources?
Improver
You can use the Allocation Tracker. Switch Exclipse into the DDMS prospective and u can find the allocation tracker control there
Francesco
+1  A: 

I got it. My solution based on Francesco answer, but onPause instead of onDestroy.

@Override
protected void onPause() {
    GridView gridView = (GridView) findViewById(R.id.public_photos);
    int count = gridView.getCount();
    for (int i = 0; i < count; i++) {
        ImageView v = (ImageView) gridView.getChildAt(i);
        if (v != null) {
            if (v.getDrawable() != null) v.getDrawable().setCallback(null);
        }
    }
    super.onPause();
}
Improver