Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

java - Remove item from arrayadapter not working

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.

question from:https://stackoverflow.com/questions/66065393/remove-item-from-arrayadapter-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...