Kotlin , android spinner onItemSelectedListener doesn't work

Am android developer and i always had a problem with spinner and its listener
this is my code
stateSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
toast(“Please select state”)
}

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        
            //  val state = stateSpinner.selectedItem as States
            val state = parent?.getItemAtPosition(position) as States
            //  toast("state id :${state.id} , state name :${state.arName}")
        
            Log.d("ccccc" , state.toString())
        
                stateId = state.id
            
                loadCities(stateId)
         
        }
    }

i write it and tested its works and after couple of days the listener not triggered or called and when i select any item of spinner nothing happens either logcat or toast or anything .

whats happening here ?

StackOverflow might be a better place to ask this kind of questions.

Anyway. From where are you calling “stateSpinner?..” ? From a fragment? Do you use kotlin synthetic and calling it from onCreateView instead of onViewCreated and stateSpinner is actually null? Log if stateSpinner is null. Just a wild guess.

2 Likes

first i put it in fragment and called in onViewCreated and as i said its stopped without i touch this fragment , and i thought that the problem from the fragment , and changed to activity and also nothing work here , someone in a telegram group hinted me that maybe the problem from the scroll view if i put it in a scroll view , i delete scroll view and nothing change

Did you fix it? Could you show me where you define stateSpinner and could you log if the spinner is acutally not null?

Does your class “State” inherit from class “View”?

If not, then I suspect you may want to try replacing
val state = parent?.getItemAtPosition(position) as State
with
val state = statesList[position]

If you give us a rough idea of what your State class looks like, we may be able to help more.

How do I bind Map<String, String> to AppCompatSpinner via data binding .
And also onItemSelected does not seem to exist for AppCompatSpinner from AndroidX.
I know it to set from ArrayAdapter , but i want to move UI logic code to xml than activity or fragments

1 Like

I replaced spinner with dialog , but i will let you know how my State class looks like

data class State ( val id :Int , val nameEn : String , val nameEr : String)

Sorry bro I don’t use data binding