3

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

avalancha
  • 1,457
  • 1
  • 22
  • 41

1 Answers1

0

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
Rubén Viguera
  • 3,277
  • 1
  • 17
  • 31
  • 1
    Sorry I cannot find a `use` method in the documentation (the one you linked or any other) and neither can I get your code example to compile or find `use` in the source code. Can you double-check your answer please and make sure we're talking about the same thing, i.e. not `recycle`? – avalancha Aug 30 '22 at 12:52