Home > Enterprise >  Show Data from Arraylist in list view in Kotlin and Android Studio
Show Data from Arraylist in list view in Kotlin and Android Studio

Time:09-18

In my code Im showing the project name in the list view. But I want to show the name of all added Contacts.

showAllContactsBtn.setOnClickListener(){

            val arrayAdapter: ArrayAdapter<Contact> = ArrayAdapter(
                this,android.R.layout.simple_list_item_1,listOfAllNames
            )
            listNames.adapter  = arrayAdapter
           listNames.setOnItemClickListener { adapterview, view, x, y ->
                Toast.makeText(this, "Contact picked"   listofAllnames[x].name, Toast.LENGTH_LONG).show()
            }

How do I show the names like in Toast "list of All names . name"?

CodePudding user response:

An ArrayAdapter just calls toString() on the items you pass in, and displays those. So you could just pass in all the name values instead:

val arrayAdapter: ArrayAdapter<Contact> = ArrayAdapter(
    this, android.R.layout.simple_list_item_1, listOfAllNames.map { it.name }
)

If you need to keep the original objects in the ArrayAdapter for whatever reason, you could override the toString() method in the objects' class so it just returns the name. But since you're just looking up an index in the original data set here, just throwing the list of labels into the ArrayAdapter constructor is probably fine!

  • Related