Search code examples
javaandroidclassandroid-arrayadapter

Dynamically Build Classes and add them to an ArrayAdapter


I have a list of populated data "neededRepData" and am trying to add this list to my adapter and having issues. Below is my Reps class and my method (from another class) to iterate through the neededRepData.

public class Reps {
    public int icon;
    public String title;

    public Reps() {
        super();
    }

    public Reps(int icon, String title) {
        super();
        this.icon = icon;
        this.title = title;
    }
}

List<Reps> listOfReps = new ArrayList<Reps>();
    for (int i = 0; i < neededRepData.size(); i++) {
        String currentRep = neededRepData.get(i);
        listOfReps.add(new Reps(R.drawable.unknown_representative, currentRep));
    }    

At this point my listOfReps has everything I expect in it. However when I create my adapter I am forced into doing something as below.

Reps customRepData[] = new Reps[]{
                       new Reps(listOfReps.get(0).icon, listOfReps.get(0).title)
    };

LocalRepAdapter adapter = new LocalRepAdapter(this, R.layout.mylist, customRepData);    

I want to pass my customRepData[] object created dynamically into my adapter, I cannot see a way to loop inside the construction of customRepData[], maybe there is a better way?

My extended ArrayAdapter class looks like this:

public class LocalRepAdapter extends ArrayAdapter<Reps> {

Context context;
int layoutResourceId;
Reps data[] = null;

public LocalRepAdapter(Context context, int layoutResourceId, Reps[] data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}    ......

Thanks.


Solution

  • You are forced to create array of classes Reps customRepData[] because the constructor of your adapter takes an array of classes but you can easily change it to

    public LocalRepAdapter(Context context, int layoutResourceId, ArrayList<Reps> list)
    

    so you no more need the Reps customRepData[] and you can just pass the listOfReps to it like

    LocalRepAdapter adapter = new LocalRepAdapter(this, R.layout.mylist, listOfReps);