0

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"?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Now it want "Contact -> Contact" like listOfAllNames.map{ Contact(it.name,it.surname } ...
@ProAslan If you're passing in a list of Contact objects then you'll have to override the Contact class's toString() method, i.e. override fun toString() = name. If you don't want to do that, and you really do need to pass Contact objects into the adapter instead of strings, you'll have to create your own custom adapter - at that point it's probably worth looking into using a RecyclerView

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.