Search code examples
androidtry-with-resourcesautocloseable

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


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


Solution

  • If you use the AutoClosable feature of a TypedArray and then you try to recycle it your application will crash: "FATAL EXCEPTION: main ... Error inflating class ..."

    I just changed old code where Lint told me to use try-with-resource statements. I had to remove the finally block where the array was recycled before.

    try (TypedArray arr = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyClass, 0, 0)){
    // do something useful with arr
    }
    

    No warnings anymore. Code works like expected.