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

Time:08-29

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?

CodePudding user response:

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