Search code examples
kotlinandroid-spinnerserializable

How to pass data to spinner


I have:

data class User( var name: String, var category: String) : Serializable

and a spinner:

val categoryList: List<Category> = ArrayList()

categoryList.add(Category("beginner", 0xFFFFFFFF.toInt()))
categoryList.add(Category("intermediate", 0xFFE57373.toInt()))
categoryList.add(Category("advanced", 0xFFFFF176.toInt()))

For save data I do this:

editTextName.text.toString(),
spinner.selectedItem.toString()

Now I want to do the same from the other way:

editTextname.setText(user.name)
spinner. ???????  (user.category)

I don't know what to put here ???????

So now I found this:

spinner.setSelection(user.category)

But setSelection() required a Int and I need a String

Maybe someone have an idea?


Solution

  • Finally I found the solution to my problem.

    var position = 0
    
    for (item in categoryList) {
        if (item.category == user.category){
           position = categoryList.indexOf(item)
        }
    }
    

    So after you can do : spinner.setSelection(position)