Home > Enterprise >  Repeated items in Android spinner
Repeated items in Android spinner

Time:11-17

I have a spinner which I call in onCreate activity. The spinner takes data from Room database. When I first run the spinner the data are shown correctly. But when I get back to the spinner I can see the same items multiple times. E.g. there should be only values of 11, 12, 13, 14 etc. not 11 or 12 twice (or sometimes even more times).

I call the function initSpinnerData() in onCreate Activity. I tried it in onResume activity, it shows the same result.

private fun initSpinnerData(){
        val allDevices = this?.let {
            ArrayAdapter<Any>(it, R.layout.simple_item_spinner, R.id.tv_simple_item)
        }
        zebraViewModel.getAllZebra()
            .observe(this, { devices ->
                devices?.forEach{
                    allDevices?.add(it)
                }
            } )
        spinner3.adapter = allDevices
        spinner3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onItemSelected(parent: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
                if (parent != null) {
                    val idZebraString = parent.getItemAtPosition(position).toString()
                    idZebra = idZebraString.toInt()
                }
            }
            override fun onNothingSelected(p0: AdapterView<*>?) {
                Toast.makeText(this@ZebraActivity, "You must choose some item", Toast.LENGTH_LONG).show()            }
        }
    }

CodePudding user response:

thats because .observe method, which gets called at start for every item and when single model changes, but you are calling add anyway, causing duplicates

try to check if this new item already exists in adapter, if yes then do nothing or remove old item and add new. e.g.

            devices?.forEach{
                if (allDevices.getPosition(it) < 0) allDevices?.add(it)
            }

that should work if you have proper model declaration (toString() and hashcode)

  • Related