1

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?

gallosalocin
  • 835
  • 1
  • 12
  • 18
  • Does this answer your question? [Android : Fill Spinner From Java Code Programmatically](https://stackoverflow.com/questions/11920754/android-fill-spinner-from-java-code-programmatically) – Nicolas Jun 18 '20 at 16:47
  • try this: https://stackoverflow.com/questions/11072576/set-selected-item-of-spinner-programmatically – Sergei Galagan Jun 19 '20 at 13:02
  • Thanks. It was very helpful but in my case something else is missing to pass : spinner.setSelection(user.category) – gallosalocin Jun 19 '20 at 16:10

2 Answers2

0

My guess is that you should pass to setSelection position of user.category in your spinner adapter. I don't know how your spinner adapter looks like, but I suppose that this should do the job

Firstly change

val categoryList: List<Category> = ArrayList()

into

val categoryList: ArrayList<Category> = ArrayList()

then use

val category = categoryList.filter { category -> category.FIRST_PROPERTY == user.category}
spinner.setSelection(categoryList.indexOf(category))

Don't forget to replace FIRST_PROPERTY with name of yours property of Category class.

Alternatively, you can use this method:

private fun selectValue(spinner: Spinner, value: Any) {
    for (i in 0 until spinner.count) {
        if (spinner.getItemAtPosition(i) == value) {
            spinner.setSelection(i)
            break
        }
    }
}
Kamil Z
  • 181
  • 12
0

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)

gallosalocin
  • 835
  • 1
  • 12
  • 18