Java – Add an arraylist to a custom ListView

Add an arraylist to a custom ListView… here is a solution to the problem.

Add an arraylist to a custom ListView

I made a custom ListView. I’m trying to populate a ListView with an Arraylist. I can successfully send data as a string to populate a ListView, but not as an ArrayList. Displays only a single row that contains all the values of the ArrayList.

Main activity

public class MainActivity extends Activity {
ArrayList<Product> products = new ArrayList<Product>();
Adapter listviewAdapter;
List arrlist = new ArrayList();  
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

arrlist.add("1");
    arrlist.add("2");

fillData();   
    listviewAdapter = new Adapter(this, products);
    ListView lvMain = (ListView) findViewById(R.id.lvMain);
    lvMain.setAdapter(listviewAdapter);
  }
  void fillData() {
      products.add(new Product(arrlist.toString(),false)); problem is here i suppose

}
}

Adapter.java

public class Adapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
Adapter(Context context, ArrayList<Product> products) {
    ctx = context;
    objects = products;
    lInflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return objects.size();
}
@Override
public Object getItem(int position) {
    return objects.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.item, parent, false);
    }
    Product p = getProduct(position);

((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
    return view;
}
Product getProduct(int position) {
    return ((Product) getItem(position));
}
}

Product.java

public class Product {
String name;
boolean selected;

Product( String items, boolean _box) {
      name = items;
      selected = _box;
  }
}

Solution

Try to add each ArrayList item to the Product object by iterating over the ArrayList:

for(String row :arrlist) {
    products.add(new Product(row, false));
}

Define arrlist as a String ArrayList instead of a generic List:

ArrayList<String> arrlist = new ArrayList<String>(); 

Related Problems and Solutions