TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Adding a Custom Object to an ArrayAdapter. How to grab Data?

This is what I have so far:

The Custom Object:

class ItemObject {
    List<String> name;
    List<String> total;
    List<String> rating;

public ItemObject(List<ItemObject> io) {
    this.total = total;
    this.name = name;
    this.rating = rating;
 }
}

The Call to the Adapter:

List<String> names, ratings, totals;

ItemObject[] io= new ItemObject[3];
io[0] = new ItemObject(names);
io[1] = new ItemObject(rating);
io[2] = new ItemObject(totals);

adapter = new ItemAdapter(Items.this, io);
setListAdapter(adapter);

Assuming the above looks ok, my questions is how would I set up the ItemAdapter, it's constructor, and unwrap the three List's from the object. And then, in the getView, assign these things:

each matching position to:

    TextView t1 = (TextView) rowView.findViewById(R.id.itemName);
    TextView t2 = (TextView) rowView.findViewById(R.id.itemTotal);
    RatingBar r1 = (RatingBar) rowView.findViewById(R.id.ratingBarSmall);

For example, position 0 in the array "names" to t1. Position 0 in the array "totals" to t1. Position 0 in the array "ratings" to r1.

EDIT: I don't want someone to write the entire Adapter. I just need to know how to unwrap the Lists from the Custom Object so I can use the data. (Something not even brought up or asked about in another question)

Upvotes: 2

Views: 7222

Answers (1)

user
user

Reputation: 87064

Your code will not work in its actual form. Do you really need lists of data in the ItemObject? My guess is no and you simply want a ItemObject that holds 3 Strings corresponding to the 3 views from your row layout. If this is the case:

class ItemObject {
    String name;
    String total;
    String rating;// are you sure this isn't a float

public ItemObject(String total, String name, String rating) {
    this.total = total;
    this.name = name;
    this.rating = rating;
 }
}

Then your lists will be merged into a list of ItemObject:

List<String> names, ratings, totals;
ItemObject[] io= new ItemObject[3];
// use a for loop
io[0] = new ItemObject(totals.get(0), names.get(0), ratings(0));
io[1] = new ItemObject(totals.get(1), names.get(1), ratings(1));
io[2] = new ItemObject(totals.get(2), names.get(2), ratings(2));
adapter = new ItemAdapter(Items.this, io);
setListAdapter(adapter);

And the adapter class:

public class ItemAdapter extends ArrayAdapter<ItemObject> {

        public ItemAdapter(Context context,
                ItemObject[] objects) {
            super(context, 0, objects);         
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // do the normal stuff
            ItemObject obj = getItem(position);
            // set the text obtained from obj
                    String name = obj.name; //etc       
                    // ...

        }       

}

Upvotes: 11

Related Questions