Search code examples
androidkotlinandroid-spinner

Android Kotlin Get Value of Selected Spinner Item


I'm using AndroidStudio 4.1.1 and kotlin

I'm having issues trying to get the value of a selected item in a spinner view/item. My first attempt, and many threads say to do it this way, is:

val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner
val selectedText = spinner.getSelectedItem().toString()

This does not work for me. selectedText shows nothing in a Toast or a println

I also tried this, which I also found many threads for:

val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner

if (spinner != null) {
    val adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, muscleGroups )
    spinner.adapter = adapter

    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
          override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                val selectedText = muscleGroups[position]
                println("Muscle Group selected is $selectedText")  // <-- this works
          }

         override fun onNothingSelected(parent: AdapterView<*>) {
            // write code to perform some action
         }
     }
}

// selectedText is not seen here:
println("Muscle Group selected is $selectedText")

This works and I can see selectedString in my println, in the onItemSelected function inside the block. But, how do I get this value to be seen outside of this block of code? I need to use this value in a class object and a database write. I've tried declaring selectedString outside/above the if (spinner != null), but that does not seem to work either.

Thanks for any help.


Solution

  • Your Spinner does not have a value selected by default. Hence calling spinner.getSelectedItem() returns null and null.toString() returns an empty String.

    Your code will work only if the user has selected an option from the Spinner first. You can set a initial value by using spinner.setSelection(position).

    If you want to use the selected value outside the selection, you can use a global variable as follows:

    val spinner = findViewById<Spinner>(R.id.wMuscleGroup) as Spinner
    var selectedText = muscleGroups.first() // as default
    
    if (spinner != null) {
        val adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, muscleGroups )
        spinner.adapter = adapter
    
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
              override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                    selectedText = muscleGroups[position]
              }
    
             override fun onNothingSelected(parent: AdapterView<*>) {
    
             }
         }
    }