【发布时间】:2012-01-10 06:53:10
【问题描述】:
我有一个显示在列表视图中的 ArrayList。现在它可以工作,但它显示了某种数组 id 看起来的名称,这就是为什么我希望它显示数组列表中每个对象的名称(字符串名称)。
每个 Product 对象都有一个字符串名称和其他值。
这是 ProductList 类,其中包含产品的 ArrayList 和将名称转换为字符串数组的方法:
import java.util.ArrayList;
public class ProductList {
ArrayList<Product> list;
public ProductList (){
list = new ArrayList<Product>();
//CREATE PRODUCT HERE
Product chicken;
list.add(new Product("Chicken", 10, 20, 30, 40, 50, 60, 70, 80, 90, 80,70,60,50,40,30));
Product rice;
list.add(new Product("Rice",11));
}
public String[] getNames (){
int c = 0;
int size = list.size() - 1;
String[] names = new String[size];
while (size >= c) {
//names.add(list.get(c).getName());
names[c] = list.get(c).getName();
c++;
}
c = 0;
return names;
}
public ArrayList<Product> getList (){
return list;
}
}
最后,这是我的 ListActivity 的代码:
public class ProductListView extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProductList pl = new ProductList();
setListAdapter(new ArrayAdapter<Product>(this, R.layout.list_item, pl.getList() ));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "View Product", Toast.LENGTH_SHORT).show();
Product product = pl.getList().get(position);
// intent stuff for product detail
Intent intent = new Intent(ProductListView.this, productdetail.class);
intent.putExtra("name",product.getName());
intent.putExtra("serving size", product.getServingSize());
intent.putExtra("calories", product.getCalories());
intent.putExtra("fat", product.getFat());
intent.putExtra("saturated fat", product.getSaturatedFat());
intent.putExtra("trans fat", product.getTransFat());
intent.putExtra("cholesterol", product.getCholesterol());
intent.putExtra("sodium", product.getSodium());
intent.putExtra("carbs", product.getCarbs());
intent.putExtra("fiber", product.getFiber());
intent.putExtra("sugar", product.getSugar());
intent.putExtra("protein", product.getProtein());
intent.putExtra("vitamina", product.getVitaminA());
intent.putExtra("vitaminc", product.getVitaminC());
intent.putExtra("calcium", product.getCalcium());
intent.putExtra("iron", product.getIron());
ProductListView.this.startActivity(intent);
//startActivity(new Intent("kfc.project.productdetail"));
}
});
}
}
我还尝试获取 ArrayList 中每个项目的所有字符串名称并将它们放入字符串数组(使用我的 getNames() 方法返回字符串数组),然后将其插入列表视图,但它只是显示运行时出错:
final ProductList pl = new ProductList();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, pl.getNames() ));
【问题讨论】:
-
那么 LogCat 中显示的错误是什么?