As was already mentioned in the comments, the standard ArrayAdapter
implementation calls toString()
on every object in your list and populates the view using the resulting String
. The simplest solution will be to override toString()
by calling your getName()
method inside it. If it doesn't suit your needs then you should create a custom adapter.
Have ArrayAdapter with list of objects to show objects containing string in a ListView
-
19-06-2023 - |
Question
I have a normal ListView:
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="10dp" />
And I populate that listview with an ArrayList of Alert objects:
// Get ListView object from XML
listView = (ListView) findViewById(android.R.id.list);
// Create a new Adapter
ArrayAdapter<Alert> adapter = new ArrayAdapter<Alert>(this, android.R.layout.activity_list_item, android.R.id.text1, DataSourceHandler.getAlertsList());
// Assign adapter to ListView
listView.setAdapter(adapter);
DataSourceHandler.getAlertsList() returns to me the ArrayList of objects and in my ListView I now see two items like this:
- path.to.object@41a92a48
- path.to.object@41a92cc8
Those two Alert objects has a method called getName() which returns a String that I want to use as the displaying name for this item in the list instead of what I get above.
How can I do this?
Solution
OTHER TIPS
Yes,override toString()
is the solution, example of doing that:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow