Reputation: 3267
I'm new to Android programming. I can get simple ListViews to work in which I use an ArrayList of strings. I want to take a step upward in complexity and have my ListView be composed of simple Java objects like this:
class myItem {
public String name;
public Integer price;
public Integer weight;
}
The ListView only needs to display the name in the above object. It doesn't have to have multiple icons, or multiple clickable actions for each item.
But I don't know where to start. All of the examples I see on the WWW are much more complicated and require me to learn things that have nothing to do with this (like a database). Or each ListView items is displayed with multiple views like text and images and icons etc. and each is clickable for a different action. I don't need any of that, and I'm getting bogged down reading about unneeded features in order to get those examples to work.
Does anyone have an example of a simple ListView that contains simple Java objects (like the one above)?
Upvotes: 1
Views: 1571
Reputation: 1006624
But I don't know where to start.
Implement a public String toString()
method on myItem
. Then create an ArrayList<myItem>
and use that instead of ArrayList<String>
, populate that list with suitable myItem
instances, and put the list into an ArrayAdapter<myItem>
instead of an ArrayAdapter<String>
. No other changes should be required -- whatever layout you are using for an ArrayAdapter<String>
will work with your ArrayAdapter<myItem>
.
In case you are new to Java, toString()
is the standard Java method for returning a String
representation of an object. The default behavior of ArrayAdapter
is to call toString()
on the object for the given list position and use that to fill in the row.
Upvotes: 2