user1809923
user1809923

Reputation: 1255

How to display dynamic data in ListView with ordering

What I want to do:

I thought I might be able to get the desired functionality using a ListView (but maybe also this is a very bad choice?). I have read some stuff about them, but still have some questions. I know that the ListView Displays data which is managed by an Adapter. If I have an ArrayAdapter, does the Listview always display the items in the order of the underlying Array in the Adapter? So to implement sorting, I would have to somehow change the Array in the Adapter? I have read, that you can use SimpleAdapter to have several properties in a row, but the data SimpleAdapter uses seems to be static. How can I achieve that?

Thanks in advance!

Upvotes: 0

Views: 374

Answers (2)

Carnal
Carnal

Reputation: 22064

Yes, ListView will represent depending on how your ArrayList or Vector([]) is sorted. Now, if you want to have several properties for each row, I would recommend that you create an Object of your choice, for instance: class Person which takes name, age, address etc etc. Then create a list which takes Person objects. Then in your getView of your ArrayAdapter that you will override, you can call Person person = getItem(position); and now you have a hold of that object in that specific row (position), and can do whatever you want with that Person object.

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Create your own adapter, and in getView() return view that matches your position. For instance if you got data like this:

id  name
0   ccc
1   bbb
2   aaa

then when you sort by id and listview wants row at position 1, you return 1 bbb. But if you sort by name ascending, and list wants row #2, then you return 0 ccc. Of course you need to maintain the "mapping", but that's rather trivial.

Upvotes: 1

Related Questions