Reputation: 126
I have made a custom ListView
. I'm trying to populate the ListView
by Arraylist
. I can successfully send data as a string to populate the ListView
but not as ArrayList
. Only single row with all the values of arraylist
is being displayed.
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;
}
}
Upvotes: 3
Views: 82
Reputation: 24848
Try add each ArrayList
item to Product
object through iterating 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>();
Upvotes: 2
Reputation: 669
Your function should be
void fillData() {
products.add(new Product("1",false));
products.add(new Product("2",false));
products.add(new Product("3",false));
}
Upvotes: 1