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

Issue

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?

Solution

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")

Answered By – Rubén Viguera

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published