I'm trying to make a spinner with custom objects. When I do getposition from spinner I get result -1. I do not know the cause
this my code:
Model
class User(var name: String?, var mail: String?) {
override fun toString(): String {
return name.toString()
}
}
Activity
val userList = ArrayList<User>()
val user1 = User("Jim","[email protected]")
userList.add(user1)
val user2 = User("John","[email protected]")
userList.add(user2)
val user3 = User("peki", "[email protected]")
userList.add(user3)
val adapter = ArrayAdapter<User>(this,
android.R.layout.simple_spinner_item, userList
)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.setAdapter(adapter)
val ambilPosisi : Int = adapter.getPosition(User("peki","[email protected]"))
Toast.makeText(this, (ambilPosisi).toString(), Toast.LENGTH_LONG).show()
Just declare your User
class as data class:
data class User(var name: String?, var mail: String?)
It will generate equals()
and toString()
methods. So you can use it in object comparison.