Search code examples
androidimageviewandroid-strictmode

ImageView setImageURI is causing strictmode error onPause


Every time I finish an application that contains a GridView with an ArrayAdapter in which I return an ImageView from getView() I get an error that says:

01-15 17:28:55.715: E/StrictMode(6480): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks. E/StrictMode(6480): java.lang.Throwable: Explicit termination method 'close' not called

The problem appears to point to several lines with:

imageView.setImageURI(uri)

Any ideas?


Solution

  • In certain situations setImageURI() opens an InputStream but doesn't close it. Here is a workaround:

    InputStream is = null;
    try { 
      if(uri != null) {
        is = getContentResolver().openInputStream(uri);
        Drawable d = Drawable.createFromStream(is, null);
        imageView.setImageDrawable(d);
      }
    } catch(Exception e) {
      Log.e(TAG, "Unable to set ImageView from URI: " + e.toString());
    } finally {
      org.apache.commons.io.IOUtils.closeQuietly(is);
    }