3

I have two models called Buyer and Car, and a custom layout called custom_row to display the rows of a ListView.

public class CustomAdapter extends BaseAdapter {
    Context c;
    ArrayList<Buyer> buyers;

    public CustomAdapter(Context c, ArrayList<Buyer> buyers) {
        this.c = c;
        this.buyers = buyers;
    }

    @Override
    public int getCount() {
        return buyers.size();
    }

    @Override
    public Object getItem(int position) {
        return buyers.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(c).inflate(R.layout.custom_row, parent, false);
        }

        TextView tvBuyerName = (TextView) convertView.findViewById(R.id.tvBuyerName);
        TextView tvCarModel = (TextView) convertView.findViewById(R.id.tvCarModel);

        final Buyer b = (Buyer) this.getItem(position);

        tvBuyerName.setText(b.getBuyerName());

        return convertView;
    }
}

So far I've only done above code, and I'm only able to display buyer's name. How to create another reference in ArrayList to model Car, so that I can get and display the information from both model Buyer and model Car in a same ListView?

Lorek Bryanson
  • 195
  • 1
  • 7
  • 22

3 Answers3

2

You could create a new class with Buyer and Car as attributes:

class Transaction{
    public Buyer buyer;
    public Car car;
}

and use it in your ArrayList (ArrayList<Transaction>).

Omar Aflak
  • 2,918
  • 21
  • 39
2

One way is create a model which contains both Car & Buyer data. By that yo can access car and buyer from same arraylist.

Another is pass two arraylist (carList & buyerList) to constructor of adapter.

ArrayList<Buyer> buyers;
ArrayList<Car> cars;

    public CustomAdapter(Context c, ArrayList<Buyer> buyers, ArrayList<Car> cars) {
        this.c = c;
        this.buyers = buyers;
        this.cars= cars;
    }

Then

final Buyer b = (Buyer) buyers.getItem(position);
tvBuyerName.setText(b.getBuyerName());

final Car c = (Car) cars.getItem(position);
tvCar.setText(c.getCarName());
Dhiraj Sharma
  • 4,364
  • 24
  • 25
1

Instead of create ArrayList of Buyer create ArrayList of Pair<Buyer,Car> like this:

ArrayList<Pair<Buyer,Car>> myBuyAndCarPair;

And when you wish to get the Buyer or the Car Objects call them like this:

Buyer myBuyer = myBuyAndCarPair.get(i).first;
Car myCar = myBuyAndCarPair.get(i).second;

To create new pair:

new Pair<>(mBuyerObject,mCarObject);
Nir Duan
  • 6,164
  • 4
  • 24
  • 38