Kotlin , android spinner onItemSelectedListener doesn't work

#1

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 ?

#2

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
#3

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

#4

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

#5

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.