Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex Items in a Listview

Tags:

android

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

I don't know which is the bext way to implement this. There's two obvious choices:

1) I can simply create the data structure outside of any Android Views, and then write a method called UpdateList() which takes the name of each item in this data structure and puts it in the ListView. The problem with this is that some of the data is duplicated twice (the original data structure, and the adapter for the ListView) and when you duplicate data, bug potential arises.

2) Or, I can somehow associate the data structure directly with the adapter for the ListView and have it figure out how to display the name for each ListView entry that is displayed. The advantage here is that you only have a single data structure. But I don't know if this is possible in Android, or very complex.

Which is the preferred way to do this with Android apps?

like image 503
JB_User Avatar asked Dec 27 '22 05:12

JB_User


1 Answers

You would be better with the ListView and the Adapter option, You would need to create a custom ArrayAdapter to populate a ListView from this objects the way you want.

The advantage of this technic is that you gain a Views recycle mechanism that will recycle the Views inside you ListView in order to spend less memory.

In Short you would have to:

1. Create an object that represents your data for a single row.

2. Create an ArrayList of those objects.

3. Create a layout that contains a ListView or add a ListView to you main layout using code.

4. Create a layout of a single row.

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

6. Create a custom ArrayAdapter that will populate the rows according to you needs.

7. Finally assign this ArrayAdapter to 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

like image 73
Emil Adz Avatar answered Jan 08 '23 01:01

Emil Adz