Search code examples
androidkotlinspinner

Kotlin Object Values from API Response as Spinner Options


I am unfortunately still quite new to Kotlin and Android.

I get a list of objects via API and want to display each list item as an option in the spinner to make a new API request based on it.

My API response looks something like this:

[User(username=a, id=1, [email protected]), 
User(username=b, id=2, [email protected]), 
User(username=c, id=3, [email protected])]

I just want to display all usernames in a spinner and when a username is selected start another API request with the ID of the selected user.

Unfortunately, I didn't find any way in the Kotlin Spinner doc and googling to set the options of a spinner in my fragment to select the name and store the ID in a variable.

Is there any way to do something like this in Kotlin without much effort or am I thinking wrong?


Solution

  • You can pass a list of Users to an ArrayAdapter:

    val list: MutableList<User> = arrayListOf(
            User("a", 1, "[email protected]"),
            User("b", 2, "[email protected]"),
            User("c", 3, "[email protected]"),
            User("d", 4, "[email protected]")
        )
    
    val arrayAdapter = ArrayAdapter(
            this,
            android.R.layout.simple_list_item_1,
            list
        )
    

    Set the adapter to your spinner:

    val spinner = findViewById<Spinner>(R.id.spinner)
    spinner.adapter = arrayAdapter
    

    Then depents your logic you can add a Button and inside it's click listener you can pick the whole selected user object:

    button.setOnClickListener {
        //Here you have the selected user with it's id
        val selectedUser = spinner.selectedItem as User
    }
    

    Or you can set an on item selected listener and pick again the whole user object:

    spinner.onItemSelectedListener =  object: AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (parent is Spinner) {
                    //Here you have the selected user with it's id
                    val selectedUser = parent.selectedItem as User
                    
                }
            }
    
            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }
        }
    

    Now to make the spinner diplay the username just overide the toString() function in your User class and return the username:

    class User(val username: String, val id: Int, val email: String) {
        override fun toString(): String {
            return username
        }
    }
    

    I hope it was what you were looking for. Also because I am new to software development I would like to see some feedback from more experienced people on whether this approach is good or not.