0

Trying to use a spinner, to make it dynamic I am using an Arrayadapter. However I am not able to remove items, it just keeps crashing. See code below.

The attribute.

private lateinit var adp : ArrayAdapter<CharSequence>

And the initialization of the adapter.

adp = ArrayAdapter.createFromResource(this,
            R.array.values_array,
            android.R.layout.simple_spinner_item)
adp.also {   adapter ->

        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter}

After one of the items has been clicked I would like to remove it from the spinner when another button is clicked, using code below.

button.setOnClickListener{
        adp.remove(spinner.selectedItem.toString())
        adp.notifyDataSetChanged()
    }

On the row of the remove, the exception java.lang.UnsupportedOperationException is thrown. Since this is the first time using Kotlin I find it hard to pin down the source of the issue.

1 Answer 1

1

If you create an ArrayAdapter using a resource array, it treats its data as immutable, meaning it will throw UnsupportedOperationException if you try to modify it. I think they overlooked adding this note to the documentation for createFromResource, but you can see it in the documentation of the constructor that it indirectly calls. Unfortunately the link isn't working through Stack Overflow, but you can find it in your IDE by Ctrl+clicking the function you're calling, and then Ctrl+clicking the constructor the createFromResource method is calling in the source code.

Work-around would be to load the resource directly and use a constructor that does not result in immutable backing data:

adp = ArrayAdapter(
    this,
    android.R.layout.simple_spinner_item,
    resources.getStringArray(R.array.values_array).toMutableList()
).apply {
        setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = this
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation, this solved it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.