Complex objects in the list

I have a ListView where the view for each item is a string (item name). But I need to associate a lot of other data with this item: price, size, weight, tax, etc. So, I create a new Java class called Item, and then an object for each item in the list.

I don’t know which bext way to implement. There are two obvious options:

1) I can simply create a data structure outside of any Android views, and then write a method called UpdateList () that takes the name of each element in this data structure and puts it in a ListView. The problem is that some data is duplicated twice (the original data structure and the adapter for the ListView), and an error occurs when duplicating the data.

2) Or I can somehow connect the data structure directly with the adapter for the ListView and figure out how to display the name for each displayed ListView entry. The advantage here is that you have only one data structure. But I do not know if this is possible in Android or very difficult.

What is the preferred way to do this using Android apps?

+4
source share
2 answers

You will be better off with the ListView and Adapter parameter, you will need to create a custom ArrayAdapter to populate the ListView from these objects the way you want.

The advantage of this technique is that you get a Rec Views engine that will process the Views inside you ListView to spend less memory.

In short you will need:

1. Create an object that represents your data for one row.

2. Create an ArrayList for these objects.

3. Create a layout containing a ListView, or add a ListView to the main layout using code.

4. Create a single line layout.

5. Create a ViewHolder that will represent the visual aspect of your data row from the Views point.

6. Create a custom ArrayAdapter that will fill the lines according to your needs.

7. Finally, assign this ArrayAdapter your ListView in onCreate .

You can get an idea of ​​how to implement this by reading this blog post, I wrote:

Create a Custom ArrayAdapter

+9
source

Just use an adapter. It is much cleaner. You can then get the information you need when displaying a list item using getView (). See this example .

+1
source

All Articles