Create references to both models in the custom adapter… here is a solution to the problem.
Create references to both models in the custom adapter
I have two mockups called Buyer
and Car
, and a custom layout called custom_row
to display the 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 have only completed the code above, and I can only display the buyer’s name. How do I create another reference to the Car model in the ArrayList
so that I can get and display information from the model Buyer
and the model Car
in the
same ListView
?
Solution
One way is to create a model that contains car and buyer data.
This way you can access cars and buyers from the same array list.
The other is to pass two array lists (carList and buyerList) to the adapter’s constructor.
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;
}
And then
final Buyer b = (Buyer) buyers.getItem(position);
tvBuyerName.setText(b.getBuyerName());
final Car c = (Car) cars.getItem(position);
tvCar.setText(c.getCarName());