我需要添加arraylist中的所有项目
logcat的:
E/BUSINESS_STR: fuflfilled
E/itemsaArrayList: [com.model.CommonListItems@307c24ff, com.model.CommonListItems@307c24ff]
代码:
if(BUSINESS_STR != null){
Log.e("BUSINESS_STR", "" + BUSINESS_STR);
CommonListItems commonListItems = new CommonListItems();
for(int i = 0; i <= 1 ; i++) {
commonListItems.setName("My Business");
commonListItems.setName("Search Business");
commonListItems.setImage(String.valueOf(R.drawable.business_icon));
commonListItems.setImage(String.valueOf(R.drawable.search_business_icon));
itemsaArrayList.add(commonListItems);
}
tvTitle.setText("Business");
}
最后,它将最后一项"Search Business"
添加两次。我需要先添加"My Business"
,然后再添加"Search Business"
。
答案 0 :(得分:1)
删除for循环:
commonListItems.setName("My Business");
commonListItems.setImage(String.valueOf(R.drawable.business_icon));
itemsaArrayList.add(commonListItems);
commonListItems = new CommonListItems();
commonListItems.setName("Search Business");
commonListItems.setImage(String.valueOf(R.drawable.search_business_icon));
itemsaArrayList.add(commonListItems);
答案 1 :(得分:1)
添加
commonListItems = new CommonListItems();
作为 for 循环中的第一个语句。现在你的代码将是这样的
if(BUSINESS_STR != null){
Log.e("BUSINESS_STR", "" + BUSINESS_STR);
CommonListItems commonListItems;
for(int i = 0; i <= 1 ; i++) {
commonListItems = new CommonListItems();
if(i==0){
commonListItems.setName("My Business" + i);
commonListItems.setImage(String.valueOf(R.drawable.business_icon));
} else {
commonListItems.setName("Search Business" + i);
commonListItems.setImage(String.valueOf(R.drawable.search_business_icon));
}
itemsaArrayList.add(commonListItems);
}
tvTitle.setText("Business");
}
答案 2 :(得分:0)
您在列表中添加CommonListItems
的相同实例 - 两次。
删除for循环并创建两个CommonListItems
类型的对象。
CommonListItems commonListItem1 = new CommonListItems();
commonListItem1.setName("My Business");
commonListItem1.setImage(String.valueOf(R.drawable.business_icon));
CommonListItems commonListItem2 = new CommonListItems();
commonListItem2.setName("Search Business");
commonListItem2.setImage(String.valueOf(R.drawable.search_business_icon));
itemsaArrayList.add(commonListItem1);
itemsaArrayList.add(commonListItem2);