Is "TypedArray should be recycled" a false positive in Lint when using try-with-resources?

473 Views Asked by At

I have read the dozens of questions here on SO regarding recycling TypedArrays, but I guess they are a bit too old and written before we could widely use try-with-resource statements, so none of them talk about using the AutoCloseable implementation of the TypedArray, which is present since API Level 31

So the question remains: is this a false positive in Lint? screenshot of Lint warning

If anything, that warning should be a minSDK warning if applicable, right? Can we simply write the following since the full try-with support (if we do it after SDK Level >= 31 check)?

try (TypedArray array = getContext().obtainStyledAttributes(attrs) {
  // Do someting
}
// End of method

My guess is yes, as this is the AutoCloseable implementation of TypedArray screenshot of docs

1

There are 1 best solutions below

1
Rubén Viguera On

So the question remains: is this a false positive in Lint?

No, it is not. Because close method in AutoCloseable interface is not magically called when using try/catch.

Instead you have to use use method and then and only then you can get rid of try/catch like following:

getContext().obtainStyledAttributes(attrs).use({
  // Do something
});

But, be aware that use method from TypedArray class is available only since Android 31

If you prefer a backwards compatible solution, you can use use method from androidx.core:core-ktx library.

As TypedArray also provides of a use method you will have to take care of adding the following import:

import androidx.core.content.res.use