Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.content.res.TypedArray cannot be cast to java.lang.AutoCloseable

Tags:

android

kotlin

I have a custom view like following which I have been able to reduce to:

class MyCustomView : FrameLayout {
  constructor(context: Context) : super(context) {
    initView(null)
  }
  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    initView(attrs)
  }

  constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int)
    : super(context, attrs, defStyleAttr) {
    initView(attrs)
  }

  private fun initView(attrs: AttributeSet?) {
    attrs?.let {
      context.theme.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0).use {
        if (it.hasValue(R.styleable.MyCustomView_my_custom_attribute)) {
          //...
        }
      }
    }
  }
}

And the problem is I'm getting an Exception: android.content.res.TypedArray cannot be cast to java.lang.AutoCloseable when executing obtainStyledAttributes method.

The same method is used all over my project but this is the only place where it is crashing. Why is that?

like image 517
Rubén Viguera Avatar asked Dec 05 '25 15:12

Rubén Viguera


1 Answers

I have realized that I was using the method use from AutoCloseable interface, but class TypedArray, which is returned by obtainStyledAttributes method, only implements it since Android 31 and I am testing on a lower API.

On places where it is working I am using use method from androidx.core:core-ktx:1.7.0 library, which is backwards compatible.

So to summarize, I only had to add the following import:

import androidx.core.content.res.use

Just in case you don't have it yet, also add the dependency to your app/library's build.gradle file

implementation("androidx.core:core-ktx:1.7.0")
like image 172
Rubén Viguera Avatar answered Dec 11 '25 14:12

Rubén Viguera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!