Adding arraylist to custom listview

I created a custom ListView

. I'm trying to fill ListView

in on Arraylist

. I can successfully send data as a string to fill ListView

, but not how Arraylist

. Only one line is displayed with all values Arraylist

.

MainActivity

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;
  }
}

      

+3


source to share


2 answers


Try to add each item ArrayList

to the object Product

through iteration ArrayList

:

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

      



Define arrlist as String

ArrayList

instead of generic type List

:

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

      

+2


source


Your function should be



void fillData() {
  products.add(new Product("1",false));
  products.add(new Product("2",false));
  products.add(new Product("3",false));
}

      

+1


source







All Articles